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.
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.