DEV Community

loading...

Discussion on: Daily Challenge #60 - Find the Missing Letter

Collapse
chrisachard profile image
Chris Achard

Here it is in JS, uses charCodeAt and fromCharCode to convert from char to ASCII number, then looks for the number difference of 2 (missing number in between them):

const missing = arr => {
  for(let i in arr) {
    const letter = arr[i]
    const next = arr[Number(i) + 1]
    if(next.charCodeAt(0) - letter.charCodeAt(0) === 2
    ) {
      return String.fromCharCode(arr[i].charCodeAt(0) + 1)
    }
  }
}
Collapse
kamaal profile image
Kamaal Aboothalib

Almost identical but I try with the functional approach and typescript
checks any number of chars instead of one.

const getDiff = (a:number, b: number):number => b - a
const getGap = (a:number, maxDiff:number = 1):number => a - maxDiff
const fillGaps = (a:number, gap:number):string[] => gap > 0 ? [...(Array(gap).fill(0))].map((_, e) => e + 1 )
    .map(i => i + a )
    .map(i => String.fromCharCode(i)) : []

const missing = (input:string[]): string => {
  return input.reduce((a, b, index, array) => {
    const positionIndex = `${b}`.charCodeAt(0)
    const nextPositionIndex:number = index + 1 < array.length ? array[index+1].charCodeAt(0) : positionIndex
    const gap = getGap(getDiff(positionIndex, nextPositionIndex), 1)
    const gaps = fillGaps(positionIndex, gap)
    return [...a,...gaps]
  }, []).join(', ')
}

codesandbox.io/s/quirky-davinci-sk826