DEV Community

Discussion on: Daily Challenge #23 - Morse Code Decoder

Collapse
 
ynndvn profile image
La blatte • Edited

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

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')
".... . -.-- .--- ..- -.. ."