Missing letters - Need help

Tell us what’s happening:

What am i missing?

Your code so far


function fearNotLetter(str) {
  var ascii = [];
  var value = 0;

  for (var i = 0; i < str.length; i++) {
    ascii.push(str.charCodeAt(i));
  }

  console.log(ascii);

  for (var j = ascii.length-1; j > 0; j--) {
    if (ascii[j] - 1 !== ascii[j-1]) {
      value = ascii[j] - 1;
      break;
    }

    else if (ascii[j] - 1 !== ascii[j-1]) {
      return undefined;
    }

  }
  console.log(value);
  return String.fromCharCode(value);
}

fearNotLetter("abce");

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:62.0) Gecko/20100101 Firefox/62.0.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/missing-letters

Aren’t the two conditions in the if and else exactly the same -

 if (ascii[j] - 1 !== ascii[j-1]) {
      value = ascii[j] - 1;
      break;
    }

 else if (ascii[j] - 1 !== ascii[j-1]) {
      return undefined;
    }

I’m not sure what your intent was there. But here’s one way to solve this using your code.

function fearNotLetter(str) {
  var ascii = [];
  var value;

  for (var i = 0; i < str.length; i++) {
    ascii.push(str.charCodeAt(i));
  }

  console.log(ascii);

  for (var j = ascii.length-1; j > 0; j--) {
    if (ascii[j] - 1 !== ascii[j-1]) {
      value = ascii[j] - 1;
      break;
    }
  }
  console.log(value);
  return value ? String.fromCharCode(value): undefined;
}

What I did here was to leave value unassigned up top. Then inside the loop, in the if block, if you find a missing letter, you assign that letter to value. There’s no need of an else.

Once you finish the loop, if there is a truthy value in value, you use String.fromCharCode() on it to get the desired result, otherwise just return value - which should be undefined at this point, because you never assigned anything to it (and which is what the problem wants if no letters are missing).

Thanks. Is there any other way i could’ve done it? with my existing code i mean.

Problem is, there’s ALWAYS another way to do it. When i tackled this, I used split(), filter(), map() and join(). there is no right answer, there’s simply your answer.

Perhaps, rather than getting tangled in the code itself, get a handle on the algorithm you use to generate the code. There’s a clear process, regardless of what language structures you use to make it a thing:

  1. break the string into individual letters.
  2. compare each letter to the next (or, if you start from the end, to the previous) for adjacency.
  3. in the event of non-adjacent letters, add the missing letter to a string.
  4. return the string.

However you choose to do it, that’s the basic breakdown.

1 Like

Thanks for the advice. I will surely keep it in mind.