Skip to content

Instantly share code, notes, and snippets.

@Daymannovaes
Created April 21, 2021 15: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 Daymannovaes/30c9bfd555f3125cf2f631829af6dc1f to your computer and use it in GitHub Desktop.
Save Daymannovaes/30c9bfd555f3125cf2f631829af6dc1f to your computer and use it in GitHub Desktop.
morse-to-word-converter.js
const symbolToMorse = {
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: '--..',
};
const morseToSymbol = {
'.-': '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',
};
const word = '100111010111001'; //19 21 25
// run all combinations and print it
function decode(word) {
let morse;
morse = binaryToMorse(word, true);
allWithOneType(morse);
// other combinations here
morse = binaryToMorse(word, false);
allWithOneType(morse);
// other combinations here
}
// type 0 -> dot = 0, dash = 1
// type 1 -> dot = 1, dash = 0
function binaryToMorse(word, type) {
const one = type ? '.' : '-';
const zero = !type ? '.' : '-';
let morse = '';
for(let letter of word) {
morse += (letter == '1') ? one : zero;
}
return morse;
}
/*
* Receive an array of letters in morse and covert to real letters
* Example:
* arrayMorseToWord(['--', '---', '.-.', '...', '.']) will return 'morse'
*/
function arrayMorseToWord(wordArray) {
let word = '';
for(let part of wordArray) {
word += morseToSymbol[part];
}
console.log(word.toUpperCase());
return word;
}
/*
* Split letters of same size into an array, and then
* convert this array of letters into a real word
*
* For example, withOneType('.--..-', 2)
* transform the word into ['.-', '-.', '.-'] which is 'nan'
*/
function withOneType(word, type) {
let length = word.length;
let begin = 0;
let wordArray = [];
while(begin < length) {
part = word.substr(begin, type);
wordArray.push(part);
begin += type;
}
arrayMorseToWord(wordArray);
}
function allWithOneType(word) {
withOneType(word, 1);
withOneType(word, 2);
withOneType(word, 3);
withOneType(word, 4);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment