Antonio Pavicevac-Ortiz
Antonio Pavicevac-Ortiz

Reputation: 7739

How do I get this 'missing letters' function to work in javaScript?

I am working on this 'Missing letters' challenge on Free Code Camp. The challenge indicates the following:

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

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

function fearNotLetter(str) {
  var newstr;
   for(var j = 0; j < str.length; j++){

       var previous = str.charCodeAt(j);
       var next = str.charCodeAt(j) + 1;


        if(next === false){
            newstr = String.fromCharCode(next);
        } else {
             return undefined;
       }
   }

  return newstr;
}

Thought I nailed it initially,

   var previous = str.charCodeAt(j);
   var next = str.charCodeAt(j) + 1;

Simply—if next is not true, e.g. the value of next is not the subsequent character or one more than previous, return newstr = String.fromCharCode(next);

Thanks in advance!

Upvotes: 2

Views: 236

Answers (2)

Yup.
Yup.

Reputation: 1893

I find this solution to be quite easy to interpret:

function fearNotLetter(str) {
  var missingLetter;
  for (var i = 0; i < str.length; i++) {
    if (str.charCodeAt(i) - str.charCodeAt(i-1) > 1) {
      missingLetter = String.fromCharCode(str.charCodeAt(i) - 1);
    }
  }
  return missingLetter;
}

Upvotes: 0

rjm27trekkie
rjm27trekkie

Reputation: 294

Try this:

function fearNotLetter(str) {
  for(var i = 0; i < str.length - 1; i++)
  {
    if(str.charCodeAt(i) + 1 != str.charCodeAt(i+1))
        return String.fromCharCode(str.charCodeAt(i) + 1);
  }
  return undefined;
}

In general setting and returning unnecessary variables is not good practice. You are not testing any condition in your if statement either. You need to actually compare the value of the character of the first index with the second. Also, since you need to compare 2 indices, your iteration must stop at go inclusive on

[0, length - 2] with a + 1 for the secondary index

or

[1, length - 1] with a - 1 for the secondary index

A Note on going to length - 1:

consider the character in the string "abcd":

a, b, c, d
0, 1, 2, 3

if i loop on [0, 3] when i try to access

str[i+1] // index 4

I will get an index out of bounds exception when i = 3 or if am index out of bounds exception when i = 0 if i try to access

str[i-1] // index -1

That is why i only iterate to one away from the given boundary

Upvotes: 2

Related Questions