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).
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:
break the string into individual letters.
compare each letter to the next (or, if you start from the end, to the previous) for adjacency.
in the event of non-adjacent letters, add the missing letter to a string.
return the string.
However you choose to do it, that’s the basic breakdown.