DEV Community

Discussion on: Daily Challenge #47 - Alphabets

Collapse
 
alvaromontoro profile image
Alvaro Montoro • Edited

JavaScript

const code = s => [...s].reduce((a, v) => v.match(/[a-z]{1}/i) 
                                          ? a+(v.toLowerCase().charCodeAt(0)-96)+' ' 
                                          : a
                        , '')
                        .trim();

And as an extra, the decoder:

const decode = s => String.fromCharCode(...s.split(' ').map(val=>parseInt(val) + 96));

Although the decoding process is not perfect, because all the spaces and symbols are lost during the coding process. For example, the sentence "The sunset sets at twelve o' clock" will be coded into:

"20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11"

Which will be decoded into:

"thesunsetsetsattwelveoclock"

Link to live demo.