JS does not have any builtin morse library, therefore we need to build it in order to use a simple oneliner:
m = { '.-': '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', '-----': '0', '.----': 1, '..---': 2, '...--': 3, '....-': 4, '.....': 5, '-....': 6, '--...': 7, '---..': 8, '----.': 9 }; decodeMorse=(s)=>s.split(' ').map(e=>m[e]||'?').join('')
And the result is:
decodeMorse('.... . -.-- .--- ..- -.. .') "HEYJUDE" // Unknown values are handled decodeMorse('...... . -.-- .--- ..- -.. .') "?EYJUDE" // And it doesn't affect "falsey" values decodeMorse('...... ----- -.-- .--- ..- -.. .') "?0YJUDE"
And here goes the encoder, using the same m variable as above
m
encodeMorse=(s)=>Object.entries(m).map(e=>s=s.replace(RegExp(e[1],'gi'),' '+e[0]))&&s.slice(1)
The encoder produces the following result:
encodeMorse('HEYJUDE') ".... . -.-- .--- ..- -.. ." encodeMorse('heyjude') ".... . -.-- .--- ..- -.. ."
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
JS does not have any builtin morse library, therefore we need to build it in order to use a simple oneliner:
And the result is:
And here goes the encoder, using the same
m
variable as aboveThe encoder produces the following result: