Find missing letter in list of alphabets

前端 未结 16 1715
逝去的感伤
逝去的感伤 2021-01-01 05:15

I am trying to solve the following issue:

Find the missing letter in the passed letter range and return it. If all letters are present in the range, return undefine

16条回答
  •  情深已故
    2021-01-01 05:26

    Note that you have a typo in alphabet: There are two "e"s.

    You could split the string into an array, then use the some method to short-circuit the loop when you don't find a match:

    function fearNotLetter(str) {
      var alphabet = 'abcdefghijklmnopqrstuvwxyz',
          missing,
          i= 0;
      
      str.split('').some(function(l1) {
        var l2= alphabet.substr(i++, 1);
        if(l1 !== l2) {
          if(i===1) missing= undefined;
          else      missing= l2;
          return true;
        }
      });
      
      return missing;
    }
    
    console.log(fearNotLetter('abce'));             //d
    console.log(fearNotLetter('bcd'));              //undefined
    console.log(fearNotLetter('abcdefghjklmno'));   //i
    console.log(fearNotLetter('yz'));               //undefined

提交回复
热议问题