JavaScript realizes Morse code encryption and decryption

Source: Internet
Author: User
Tags add array object end string split trim hasownproperty


Morse code is a time and time to break signal codes, in different order to express different English letters, numerals and punctuation, was invented by the American Samuel Morse in 1836.
Each character (letter or number) corresponds to a different sequence (consisting of dots and strokes).
In general, any encoding that can represent a written character with a variable-length signal can be called Morse code.
But the term is now used to refer only to two Morse codes that represent English letters and symbols: American Morse code and international Morse code. The following content is only for international Morse code.



Letters, numbers, punctuation, special characters and Morse code comparison



Letters
Letters, morse Code, Morse code, Morse code, Morse code, and Morse code.
--- ---- --- --- --- ---- --- --- --- ----
A.-B-...C-.-.D-..E.
F..-.G--.H....I..J.---
K-.-L.-..M--N-.O---
P.--.Q--.-R.-.S...T-
U..-V...-W.--X-..-Y-.--
Z--..



Digital
Digital Morse code digital Morse code digital morse code Morse code digital Morse Code
--- ---- --- --- --- ---- --- --- --- ----
1.----2..---3...--4....-5.....
6-....7--...8---..9----.0-----



Punctuation
Character Fumos code word Fumos code word Fumos code word Fumos code word Fumos Code
--- ---- --- --- --- ---- --- --- --- ----
..-.-.-:---...,--..--;-.-.-.?..--..
=-...-'.----./-..-.!-.-.----....-
_..--.-".-..-.(-.--.)-.--.-$...-..-
&.-...@.--.-.+.-.-.



Special characters
There are special characters that represent specific meanings, such as SOS (Emergency Help), which can be used to deliver information with fewer Morse codes.
Character Fumos code word Fumos Code
--- --- --- ---
AA, line of.-.-AR, end.-.-.of message
As, waiting for.-...BK, interrupted-...-.-
BT, new one-page-...-CT, start copy-.-.-
SK, End delivery...-.-SOS, emergency help...---...



In addition to the above characters, can also be through the sound or light and other media to pass Morse password information, to sound as an example, tick (short sound), the representative (long sound).



Morse code related events


    1. The Japanese were executed by Isis some time ago, in the course of the punishment of his blinking behavior by Morse code experts read through the blink of an eye to convey information, translated into words as "Don't save me, give me up!" ”
    2. The SOS signal was also sent before the 1912 sinking of the Titanic cruise ship.


JavaScript realizes Morse code encryption parsing


    1. Using a dictionary to achieve the corresponding relationship between Morse code and character, the dictionary is also based on the object to implement
    2. The lower version of IE cannot be indexed by the subscript to traverse the string
    3. ie there is a bug in Str.split (REGEXP)


Online Demo



Complete code:


/ *
* @author liaoyu
* @created 2015-03-14
* /

var utils = utils {};

utils.isArray = function (value) {
    return Object.prototype.toString.apply (value) === '[object Array]';
}

utils.trim = function (value) {
    return value.trim? value.trim (): value.replace (/ ^ \ s + \ s + $ / g, '');
}

// Solve the problem of IE incompatible console
var console = console {};
console.log = console.log function () {};
console.error = console.error function () {};

// Use a dictionary to store the Morse code comparison relationship
function Dictionary () {
    this.datasource = {};
    this.rdatasource = {};
}

Dictionary.prototype.add = function (keys, values) {
    if (typeof keys === 'undefined' typeof values === 'undefined') {
        console.error ('Illegal arguments');
        return;
    }
    if (utils.isArray (keys) && utils.isArray (values)) {
        if (keys.length! = values.length) {
            console.error ('keys length not equals values length');
            return;
        }
        for (var i = 0; i <keys.length; i ++) {
            this.datasource [keys [i]] = values [i];
        }
        return;
    }
    this.datasource [keys] = values;
}

Dictionary.prototype.reversal = function () {
    var tempData = this.datasource;
    for (var i in tempData) {
        if (tempData.hasOwnProperty (i)) {
            this.rdatasource [tempData [i]] = i;
        }
    }
}

Dictionary.prototype.showAll = function (values) {
    var count = 0;
    console.log ('----------- morse code mapping -----------');
    for (var i in values) {
        if (values.hasOwnProperty (i)) {
            count ++;
            console.log (i + '\ t>' + values [i]);
        }
    }
    console.log ('total count:' + count);
}

// morse code library
var morse = (function (global) {
    var mcode = {},
        r_special = / \ <\ w + \> / g,
        r_find = / ^ \ <(\ w +) \> $ /;

    // store datas mapping
    mcode.mdatas = (function () {
        var dictionaryDS = new Dictionary ();
        // initial mappping
        dictionaryDS.add (
            [
                'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M ',' N ',' O ',' P ',' Q ',' R ',' S ',' T ',' U ',' V ',' W ',' X ',' Y ', 'Z',
                '1', '2', '3', '4', '5', '6', '7', '8', '9', '0',
                'AA', 'AR', 'AS', 'BK', 'BT', 'CT', 'SK', 'SOS',
                '.', ':', ',', ';', '?', '=', "'",' / ','! ','-',' _ ',' "',' ( ',') ',' $ ',' & ',' @ ',' + '
            ],
            [
                // letter
                '.-', '-...', '-.-.', '-..', '.', '..-.', '-.', '....', ' .. ',' .--- ',' -.- ',' .- .. ','-','-. ',' --- ',' .--. ','- .- ',' .-. ',' ... ','-',' ..- ',' ...- ',' .-- ',' -..- ',' -.- -','-.. ',
                // number
                '.----', '..---', '...--', '....-', '.....', '-....', '- -... ',' --- .. ',' ----. ',' ----- ',
                // special charactor
                '.-.-', '.-.-.', '.-...', '-...-.-', '-...-', '-.-.-', ' ...-.- ',' ...---... ',
                // punctuation
                '.-.-.-', '---...', '--..--', '-.-.-.', '..-- ..', '-... -',' .----. ',' -..-. ',' -.-.-- ',' -....- ',' ..--.- ',' .- ..-. ',' -.--. ',' -.--.- ',' ...-..- ',' .-... ',' .--.-. ', '.-.-.'
            ]
        );
        return dictionaryDS;
    } ());
    
    // error flag
    mcode.error_flag = false;

    // Convert string to Morse code
    mcode.parse = function (values) {
        // console.log ('input:' + values);
        this.error_flag = false;

        var _datasource = this.mdatas.datasource,
            item = '',
            a_special = [],
            a_temp = [],
            a_value = [],
            count = 0,
            result = '';
        values = values.toUpperCase ();
        a_special = values.match (r_special);
        a_temp = values.split (r_special);

        // Convert the string entered by the user into an array
        for (var i = 0; i <a_temp.length; i ++) {
            item = a_temp [i];
            if (item! == '') {
                // IE cannot index strings by subscript
                if (! item [0]) {
                    item = item.split ('');
                }
                for (var j = 0; j <item.length; j ++) {
                    a_value [count ++] = item [j];
                }
            }

            // The current string is in the form of <AS>, extract AS characters
            if (i! == a_temp.length-1) {
                a_value [count ++] = a_special [i] .match (r_find) [1];
            }
        }

        // The user input value in the form of an array will be parsed
        for (var i = 0; i <a_value.length; i ++) {
            item = a_value [i];

            if (item === '') {
                result + = '/';
            } else if (typeof _datasource [item] === 'undefined') {
                this.error_flag = true;
                // console.error ('Invalid characters in input.')
                result + = '?';
            } else {
                result + = _datasource [item] + '';
            }
        }
        return utils.trim (result);
    }

    // Convert the Morse code to a string
    mcode.decode = function (values) {
        // console.log ('input:' + values);
        this.error_flag = false;

        this.mdatas.reversal ();
        var _rdatasource = this.mdatas.rdatasource,
            a_input = values.split (''),
            result = '',
            item = '',
            c_result = '';

        for (var i = 0; i <a_input.length; i ++) {
            item = a_input [i];
            if (item=== '/') {
                 result + = '';
             } else {
                 c_result = _rdatasource [item];
                 if (typeof c_result === 'undefined') {
                     this.error_flag = true;
                     // console.error ('Invalid characters in input.')
                     result + = '?';
                 } else {
                     if (c_result.length> 1) {
                         result + = '<' + c_result + '>';
                     } else {
                         result + = c_result;
                     }
                 }
             }
         }
         return result;
     }

     return mcode;
} (this));


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.