0

I've been dealing with an algorithm which takes a sequence of letters in alphabetic order, and if there is a character missing, it returns that character.

For example: fearNotLetter("abcdfg") would return "e".

My questions are:

What is the logic behind this solution?

Why and how regex is used here?

How does the condition in the for loop work?

function fearNotLetter(str) {
  var allChars = '';
  var notChars = new RegExp('[^'+str+']','g');

  for (var i = 0; allChars[allChars.length-1] !== str[str.length-1] ; i++)
    allChars += String.fromCharCode(str[0].charCodeAt(0) + i);

  return allChars.match(notChars) ? allChars.match(notChars).join('') : undefined;
}
Peter Peach
  • 159
  • 10
  • Negated character class. Matches any character but the characters it contains. Note that the function would fail if the `str` parameter contained a `]`, since it would close the character class (e.g. `fearNotLetter("abc]gotcha")` would create the `[^abc]gotcha]` regex which would only match `Xgotcha]` where X isn't a, b, nor c) – Aaron Oct 03 '18 at 13:54
  • Possible duplicate of [Learning Regular Expressions](https://stackoverflow.com/questions/4736/learning-regular-expressions) – Aaron Oct 03 '18 at 13:54

1 Answers1

2
function fearNotLetter(str) {
   var allChars = '';
   var notChars = new RegExp('[^'+str+']','g'); //1

   for (var i = 0; allChars[allChars.length-1] !== str[str.length-1] ; i++)//2
      allChars += String.fromCharCode(str[0].charCodeAt(0) + i); 

   return allChars.match(notChars) ? allChars.match(notChars).join('') : undefined; //3
}
  1. As the variable name says, it creates a negate of str which means like !abcdfg
  2. Loop, build the full correct string until the last character of str, means full letters of the alphabet untill character g => abcdefg
  3. Then it compares with match method of string the full text with the provided text: dummy way you can think

    abcdefg - abcdfg then you get e, if there are multiple characters are missing it concatenates with join method.

Ntwobike
  • 2,406
  • 1
  • 21
  • 27