Skip to content

Instantly share code, notes, and snippets.

@doxyf
Created October 31, 2022 16:58
Show Gist options
  • Save doxyf/902c366025d9b3f1758f1d33069e0bb4 to your computer and use it in GitHub Desktop.
Save doxyf/902c366025d9b3f1758f1d33069e0bb4 to your computer and use it in GitHub Desktop.
Translate human readable text to morse code
const readline = require('node:readline');
const { stdin: input, stdout: output } = require('node:process');
const rl = readline.createInterface({ input, output });
rl.question('Enter text: ', (answer) => {
console.log(translate(answer));
rl.close()
});
let dict = {
"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": "--..",
".": ".-.-.-",
",": "--..--",
"?": "..--..",
"!": "-.-.--",
"-": "-....-",
"/": "-..-.",
"@": ".--.-.",
"(": "-.--.",
")": "-.--.-",
" ": " "
}
/**
* @param {string} str String you want to translate to morse
* @returns {string} A morse version of input
*/
function translate(str){
let result = '';
str.split('').forEach(char => {
result += `${dict[char.toLowerCase()] || '?'}|`
});
return result.slice(0, -1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment