js decoding morse code
javascript, morse-code
Solution
Here is a method that uses `.map()`, `.split()`, and `.join()`.
function decodeMorse(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);
Problem
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 time getting past the word spaces. I keep getting "wordundefinedword". ``` decodeMorse = function(morseCode) { outPut = ""; for (var i = 0; i < morseCode.split(" ").length; i++) { if (i === " ") { outPut += " "; } else { outPut += MORSE_CODE[morseCode.split(" ")[i]]; } } return outPut; } ``` Example: "".... . -.--" "-- .- -."" -> "HEY MAN" Sorry for the weird quotes. It wouldn't show the spaces without the outer ones.