Skip to content

Instantly share code, notes, and snippets.

@vitaliisili
Created February 21, 2019 00:03
Show Gist options
  • Save vitaliisili/35695ff51c1d569a003e06694087011c to your computer and use it in GitHub Desktop.
Save vitaliisili/35695ff51c1d569a003e06694087011c to your computer and use it in GitHub Desktop.
decode string to Morse
decodeStringToMorse = function(morseCode){
const morseAlphabet = {
"-----":"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",
" ":" ",
"-.-.--":"!",
".-.-.-":".",
"--..--":",",
"...---...":"sos"
};
let str = '';
let arr = [];
let count = 0;
function con() {
arr.push(str);
}
for (let i = 0; i < morseCode.length; i++) {
if (morseCode[i] == ' ') {
count++;
if (count == 3) {
count = 0;
str += ' ';
con();
str = '';
}
}
else if (morseCode[i + 1] != ' ' && (i + 1) != morseCode.length) {
str += morseCode[i];
count = 0;
}
else if (morseCode[i + 1] == ' ' || (i + 1) == morseCode.length) {
str += morseCode[i];
con();
str = '';
}
}
function morseToString (array) {
let result = '';
for (let i = 0; i < array.length; i++) {
result += morseAlphabet[array[i]]
}
return result.toUpperCase().trim();
}
return morseToString(arr)
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment