mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-05 08:16:50 +08:00

* chore: Switch to Node 20 + Vitest * chore: migrate to vitest mock functions * chore: code style (switch to prettier) * test: re-enable long-running test Seems the switch to Node 20 and Vitest has vastly improved the code's and / or the test's runtime! see #1193 * chore: code style * chore: fix failing tests * Updated Documentation in README.md * Update contribution guidelines to state usage of Prettier * fix: set prettier printWidth back to 80 * chore: apply updated code style automatically * fix: set prettier line endings to lf again * chore: apply updated code style automatically --------- Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Co-authored-by: Lars Müller <34514239+appgurueu@users.noreply.github.com>
91 lines
1.8 KiB
JavaScript
91 lines
1.8 KiB
JavaScript
/**
|
|
* @author mrmagic2020
|
|
* @description Enciphers a combination of letters, numbers and symbols into morse code.
|
|
* @see https://en.wikipedia.org/wiki/Morse_code
|
|
* @param {string} msg The message to be enciphered.
|
|
* @param {string} dot Symbol representing the dots.
|
|
* @param {string} dash Symbol representing the dash.
|
|
* @returns {string} Enciphered morse code.
|
|
* @example morse('Hello World!') = '**** * *-** *-** --- *-- --- *-* *-** -** -*-*--'
|
|
*/
|
|
const morse = (msg, dot = '*', dash = '-') => {
|
|
const key = {
|
|
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: '-----',
|
|
'.': '*-*-*-',
|
|
',': '--**--',
|
|
'?': '**--**',
|
|
'!': '-*-*--',
|
|
"'": '*----*',
|
|
'"': '*-**-*',
|
|
'(': '-*--*',
|
|
')': '-*--*-',
|
|
'&': '*-***',
|
|
':': '---***',
|
|
';': '-*-*-*',
|
|
'/': '-**-*',
|
|
_: '**--*-',
|
|
'=': '-***-',
|
|
'+': '*-*-*',
|
|
'-': '-****-',
|
|
$: '***-**-',
|
|
'@': '*--*-*'
|
|
}
|
|
|
|
let newMsg = ''
|
|
|
|
msg
|
|
.toString()
|
|
.split('')
|
|
.forEach((e) => {
|
|
if (/[a-zA-Z]/.test(e)) {
|
|
newMsg += key[e.toUpperCase()]
|
|
.replaceAll('*', dot)
|
|
.replaceAll('-', dash)
|
|
} else if (Object.keys(key).includes(e)) {
|
|
newMsg += key[e].replaceAll('*', dot).replaceAll('-', dash)
|
|
} else {
|
|
newMsg += e
|
|
}
|
|
newMsg += ' '
|
|
})
|
|
|
|
return newMsg.trim()
|
|
}
|
|
|
|
export { morse }
|