Skip to content

Instantly share code, notes, and snippets.

@louislatreille
Created August 23, 2021 00:05
Show Gist options
  • Save louislatreille/a01f52c581c74dfeb263520bf4a9a6db to your computer and use it in GitHub Desktop.
Save louislatreille/a01f52c581c74dfeb263520bf4a9a6db to your computer and use it in GitHub Desktop.
(Article) You should aim to forget how your code works
const decodeMorse = (morseCode) => {
return morseCode
.trim()
// Each Morse code words are split by 3 spaces, and each letters are split by 1 space.
// The order of the two sequences below is important. We always check for 2 spaces first
// and then for one space. This allows to split all letters properly because 2 spaces
// will not match one space. If we do hit a 3 spaces sequence, we will first split on
// the 2 spaces, which will leave us with a right substring starting with 1 space.
// This will then be split again because of the trailing space. The 3 spaces will then
// result in 3 substrings. The expected left substring letter, an empty string, and the
// expected right substring letter.
// Ex. '..-. --- --- -... .- .-.' will result in
// ['..-.', '---', '---', '', '-...', '.-', '.-.']
.split(/ | /)
// Based on the above split, each Morse letter will be translated directly from the
// dictionary. The empty strings will result in undefineds, thus the right side of the
// OR will be evaluated and return a space.
.map( (code) => MORSE_CODE[code] || ' ')
.join('');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment