Skip to content

Instantly share code, notes, and snippets.

@keif
Last active August 29, 2015 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save keif/22461ed1ac197949ba3a to your computer and use it in GitHub Desktop.
Save keif/22461ed1ac197949ba3a to your computer and use it in GitHub Desktop.
A generic morse code encode/decode exercise.
var charCodes= {
"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": "_ _ _ _ _"
};
var encodeMorse = function (string) {
var chars = string.toLowerCase().split("");
var value = "";
for (var a = 0; a < chars.length; a++) {
if (charCodes[chars[a]]) {
value += charCodes[chars[a]] + " ";
}
}
return value;
};
var decodeMorse = function (string) {
var morseChars = string.split(" ");
var value = "";
for (var a = 0; a < morseChars.length; a++) {
if (morseChars[a].length && morseChars[a] !== " ") {
value += getKeyByValue(morseChars[a], charCodes);
}
}
return value;
};
var getKeyByValue = function (keyValue, object) {
for (var prop in object) {
if (object.hasOwnProperty(prop)) {
if (object[prop] === keyValue) {
return prop;
}
}
}
};
var count = function (string, char) {
var re = new RegExp(char,"g");
return string.match(re).length
};
var countDashes = function (string) {
return count(string, "_");
};
var countDots = function (string) {
return count(string, "\\.");
};
var countDashesAndDots = function (string) {
var numOfDashes = countDashes(string);
var numOfDots = countDots(string);
return ("There are " + numOfDashes + " dashes and there are " + numOfDots + " dots.");
};
var word = "Testing!";
var morse = encodeMorse(word);
var text = decodeMorse(morse);
console.log("Original word: " + word);
console.log("Encoded word: " + morse);
console.log(countDashesAndDots(morse));
console.log("Decoded morse: " + text);
@keif
Copy link
Author

keif commented Apr 20, 2015

Just a generic exercise - want to revisit with map and filter instead of loops, and revisit performance.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment