DEV Community

loading...

Discussion on: Daily Challenge #254 - The Vowel Code

Collapse
willsmart profile image
willsmart • Edited

Let's do it in JS using neat little generic HOF...

const
    codeFunctionForMapping = replacementMapping => (
      inputString => inputString.replace(/./g, c => replacementMapping[c] || c)
    ),
    encode = codeFunctionForMapping({a:1, e:2, i:3, o:4, u:5}),
    decode = codeFunctionForMapping({1:'a', 2:'e', 3:'i', 4:'o', 5:'u'})

Bit of a sanity check:

> encode('hello')
< "h2ll4"

> decode('h2ll4')
< "hello"

> encode('Step 1: Create a function called encode() to replace all the lowercase vowels in a given string with numbers according to the following pattern:')
< "St2p 1: Cr21t2 1 f5nct34n c1ll2d 2nc4d2() t4 r2pl1c2 1ll th2 l4w2rc1s2 v4w2ls 3n 1 g3v2n str3ng w3th n5mb2rs 1cc4rd3ng t4 th2 f4ll4w3ng p1tt2rn:"

> decode('St2p 1: Cr21t2 1 f5nct34n c1ll2d 2nc4d2() t4 r2pl1c2 1ll th2 l4w2rc1s2 v4w2ls 3n 1 g3v2n str3ng w3th n5mb2rs 1cc4rd3ng t4 th2 f4ll4w3ng p1tt2rn:')
< "Step a: Create a function called encode() to replace all the lowercase vowels in a given string with numbers according to the following pattern:" 
    // Well, I prefer alpha bullets anyway :|

Edit: inputString => inputString.replace(/./g, c => replacementMapping[c] ?? c) is a less supported but better choice -- caniuse.com/#search=%3F%3F

Collapse
miketalbot profile image
Mike Talbot

Very nice

Collapse
willsmart profile image
willsmart

Cheers