Skip to content

Instantly share code, notes, and snippets.

@YaxelPerez
Last active May 13, 2019 18:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save YaxelPerez/563748a1427990a8e7b7189dca7c6e71 to your computer and use it in GitHub Desktop.
Save YaxelPerez/563748a1427990a8e7b7189dca7c6e71 to your computer and use it in GitHub Desktop.
Generate morse code from text.
const morse_code = {
'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': '-----',
'.': '.-.-.-',
',': '--..--',
'?': '..--..',
"'": '.----.',
'!': '-.-.--',
'/': '-..-.',
'(': '-.--.',
')': '-.--.-',
'&': '.-...',
':': '---...',
';': '-.-.-.',
'=': '-...-',
'+': '.-.-.',
'-': '-....-',
'_': '..--.-',
'"': '.-..-.',
'$': '...-..-',
'@': '.--.-.'
};
function char_to_pattern(char) {
const pattern = [];
const code = morse_code[char].split('');
for (i = 0; i < code.length; i++) {
if (code[i] === '.') {
pattern.push(1);
} else if (code[i] == '-') {
pattern.push(3);
}
if (i < code.length - 1) {
pattern.push(1);
}
}
return pattern;
}
function str_to_pattern(str) {
let pattern = [];
for (let i = 0; i < str.length; i++) {
const c = str.charAt(i);
const next_c = str.charAt(i + 1);
if (c.trim().length === 0) { // skip whitespace
continue;
}
pattern = pattern.concat(char_to_pattern(c));
if (next_c.trim().length === 0) {
pattern.push(7);
} else {
pattern.push(3);
}
}
return pattern;
}
// Explanation for 1200 / wpm
// https://en.wikipedia.org/wiki/Morse_code#Speed_in_words_per_minute
function pattern_to_timings(pattern, wpm) {
return pattern.map(i => (i * (1200 / wpm)).toString()).join(',');
}
const replacements = [
[/</g, ' LT '],
[/>/g, ' GT '],
[/\*/g, ' star '],
[/#/g, ' hash ']
];
function cleanup(str) {
str = str
.toLowerCase()
.normalize('NFD')
.replace(/[\u0300-\u036f]/g, '');
for (let i = 0; i < replacements.length; i++) {
str = str.replace(replacements[i][0], replacements[i][1]);
}
str = str.replace(/\s+/g, ' ');
return str;
}
function morse(str, wpm) {
return '0,' + pattern_to_timings(
str_to_pattern(cleanup(str)),
wpm
);
}
vibratePattern(morse(text, 15));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment