Skip to content Skip to sidebar Skip to footer

Js Decoding Morse Code

For this project, I am trying to decode a given Morse code string. Encoded characters are separated by a single space and words are separated by three spaces. I am having a tough t

Solution 1:

Here is a method that uses .map(), .split(), and .join().

functiondecodeMorse(morseCode) {
  var ref = { 
    '.-':     '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',
  };

  return morseCode
    .split('   ')
    .map(
      a => a
        .split(' ')
        .map(
          b => ref[b]
        ).join('')
    ).join(' ');
}

var decoded = decodeMorse(".-- --- .-. -..   .-- --- .-. -..");
console.log(decoded);

Solution 2:

Maybe have two loops nested instead. The outside loop splits your morse code by three spaces, and the inner loop splits the word by one space. That will parse out the letter, then you can map the alpha-numeric character by using an enum of the morse code letters.

// message = Halp! Morse code is driving me nuts!var message = ".... .- .-.. .--. -·-·--     -- --- .-. ... .     -.-. --- -.. .     .. ...     -.. .-. .. ...- .. -. --.     -- .     -. ..- - ... -·-·--"; 
var alphabet = {  
   "-----":"0",
   ".----":"1",
   "..---":"2",
   "...--":"3",
   "....-":"4",
   ".....":"5",
   "-....":"6",
   "--...":"7",
   "---..":"8",
   "----.":"9",
   ".-":"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",
   "/":" ",
   "-.-.--":"!",
   ".-.-.-":".",
   "--..--":","
};
var messageConverted = [];

message.split("   ").map(function (word) {
    word.split(" ").map(function (letter) {
        messageConverted.push(alphabet[letter]);
    });
    messageConverted.push(" ");
});
 
console.log(messageConverted.join(""));

Or something like that. That enum is not complete (caps, punctuation), but you get the idea.

Solution 3:

decodeMorse = function( morseCode ) {
    return morseCode
             .split("   ") // get word code 3 spaces apart
             .map(word => word
                           .split(" ") // get character code 1 spaces apart
                           .map(character =>MORSE_CODE[character]) // decode Morse code character
                           .join('')
              )
              .join(' ') // add spaces between words 
              .trim()
}

decodeMorse('.... . -.--   .--- ..- -.. .') // "HEY JUDE"decodeMorse(' . ') // "E"

It works fine on codewars.com. If not codewars.com you need to define morse characters:

var MORSE_CODE = {  
        "-----":"0",
        ".----":"1",
        "..---":"2",
        "...--":"3",
        "....-":"4",
        ".....":"5",
        "-....":"6",
        "--...":"7",
        "---..":"8",
        "----.":"9",
        ".-":"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",
        "-.-.--":"!",
        ".-.-.-":".",
        "--..--":","
    };

Hope my code can help you.

Solution 4:

Sample Morse message:

var message = ".... .- .-.. .--. -.-.--     -- --- .-. ... .     -.-. --- -.. .     .. ...     -.. .-. .. ...- .. -. --.     -- .     -. ..- - ... -.-.--"; 

Morse dictionary:

var dictionary= {  
   "-----":"0",
   ".----":"1",
   "..---":"2",
   "...--":"3",
   "....-":"4",
   ".....":"5",
   "-....":"6",
   "--...":"7",
   "---..":"8",
   "----.":"9",
   ".-":"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",
   "-.-.--":"!",
   ".-.-.-":".",
   "--..--":","
};

Search for a pattern starting with . or - and translate it:

var representation = message.replace(/([.-]+[-.]*)/g, (_, x) =>dictionary [x]);
console.log(representation);

Solution 5:

Another solution that based on 2 loops. The seperation of words in the morse code made by split(" ") - (with 3 separation signs) - which splits the morse code into words when it recognize 3 seperation signs. Now you have an array of x strings. In order to get an access to every element (a letter) in the morse code you should make another split by looping over the array of strings (you can use "map") but now with split(" ") -(with 1 separation signs). now you have an array that contain sub arrays which every one represent a word (in morse code of course). In order to loop over the dictionary of the morse code (an object) you can convert it into array by Object.keys etc and then find the specific letter (in morse) in the converted array (search the specific key).

an example of morse code:

 decodeMorse('.... . -.--   .--- ..- -.. .');
 //should return:"HEY JUDE"

the function:

decodeMorse = function(morseCode){ 
  var ind=0;
  var answer = [];
  const TOT_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", ".---- 
  ":"1", "..---":"2", "...--":"3", "....-":"4", ".....":"5", 
  "-....":"6", "--...":"7", "---..":"8", "----.":"9", "----- 
  ":"0", "|":" "
  };

  const moerse_keys = Object.keys(TOT_MORSE_CODE);/*converting 
  the object into an array*/const moerse_values = Object.values(TOT_MORSE_CODE);
  var words_in_morse = morseCode.split ('   ');
  /*sperating the morse code by words*/var letters_in_morse = 
       words_in_morse.map(word => word.split(' '));
  /*sperating the morse code by letters for each word*/for (i=0 ; i<letters_in_morse.length ; i++) {
    for (j=0 ; j<letters_in_morse[i].length ; j++) {
       if ( moerse_keys.includes(letters_in_morse[i][j]) ) {
         ind = moerse_keys.indexOf( letters_in_morse[i][j] );
         answer.push(moerse_values[ind]);
       }
       if (j===letters_in_morse[i].length-1 ) { /*for seperate 
          words by ' '*/
          answer.push(' ');
       }
    }
  }

  answer.pop(); /*to remove the last ' ' (avoiding getting 
  "HEY JUDE ")*/return answer.join('').toUpperCase();
}

Post a Comment for "Js Decoding Morse Code"