Friday, July 24, 2020

Missing letters

From: https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/missing-letters

Intermediate Algorithm Scripting: Missing letters


Find the missing letter in the passed letter range and return it.

If all letters are present in the range, return undefined.


fearNotLetter("abce") should return "d".

fearNotLetter("abcdefghjklmno") should return "i".

fearNotLetter("stvwx") should return "u".

fearNotLetter("bcdf") should return "e".

fearNotLetter("abcdefghijklmnopqrstuvwxyz") should return undefined.


const fearNotLetter = str => 
  str.split('').reduce((a, b, i, letters) => 
      b.charCodeAt(0) - a.charCodeAt(0) === 1 ?
          (i < letters.length - 1 ? b : undefined)
      :
          (letters.splice(i), String.fromCharCode(a.charCodeAt(0) + 1))   
  );

[
    "abce",
    'abcdefghjklmno',
    'stvwx',
    'bcdf',
    'abcdefghijklmnopqrstuvwxyz'
].forEach(param => console.log(fearNotLetter(param)));

Output:
d
i
u
e
undefined

No comments:

Post a Comment