DEV Community

loading...

Discussion on: Daily Challenge #254 - The Vowel Code

Collapse
qm3ster profile image
Mihail Malo • Edited

JavaScript

normal (aka filthy coercion)

const letters = ['a', 'e' ,'i', 'o', 'u']
const letters_ex = /a|e|i|o|u/g
const numbers_ex = /[1-5]/g
// dirty coercion
const encode = str => str.replace(letters_ex, c => letters.indexOf(c) + 1)
const decode = str => str.replace(numbers_ex, c => letters[/*parseInt*/(c) - 1])

sneaky

const letters = [/*undefined*/, 'a', 'e' ,'i', 'o', 'u']
const letters_ex = /a|e|i|o|u/g
const numbers_ex = /[1-5]/g

const encode = str => str.replace(letters_ex, c => letters.indexOf(c))
const decode = str => str.replace(numbers_ex, c => letters[c]) // oh yes, real life string indexing

generic

const maek = (...letters) => {
  const len = letters.length;
  if (len < 1 || len > 9) throw "💩"
  const letters_ex = new RegExp(letters.join('|'), 'g')
  const numbers_ex =  new RegExp(`[1-${letters.length}]`, 'g')
  const l = [, ...letters]
  const encode = str => str.replace(letters_ex, c => l.indexOf(c))
  const decode = str => str.replace(numbers_ex, c => l[c])
  return {encode, decode}
}

const {encode, decode} = maek('a', 'e' ,'i', 'o', 'u')