-2

In this code I want to return the alphabet that's missing in a string of continuous alphabets, and if all alphabets are present I want to return undefined. However, instead returning defined, it returns "{" and I can't find similar cases anywhere online.

function fearNotLetter(str) {

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

console.log(fearNotLetter("abcdefghijklmnopqrstuvwxyz"))
VLAZ
  • 26,331
  • 9
  • 49
  • 67
tommy-ling
  • 49
  • 9
  • 5
    [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) and [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/q/25385173) – VLAZ Mar 03 '22 at 12:31
  • 3
    change the for loop to `for (let i = 0; i < str.length - 1; i++) {` - so you don't test the last letter because `"z"` is not the letter before `undefined` – Bravo Mar 03 '22 at 12:31
  • @Bravo totally missed that piece of logic. Thanks a lot for pointing out – tommy-ling Mar 03 '22 at 12:40

2 Answers2

1

Your code compares each letter with the letter following it in the string

You can't test the last letter, since nothing comes after it

simply change the loop so it only iterates to the second last letter

function fearNotLetter(str) {

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

console.log(fearNotLetter("abcdefghijklmnopqrstuvwxyz"))
Bravo
  • 6,022
  • 1
  • 10
  • 15
0

here in your example inside for loop you are returning

String.fromCharCode(str.charCodeAt(i)+1)

in this return value when charecter is z , where has ascii value of 'z' is 122 and you are returning 122+1 that is asci value of '{'

thats why you are getting '{' in your example

you can test by removing 'z' from passed string in your function

  • if you remove the `z`, then the code will return `"z"` ... not `undefined` - how can this be the accepted answer!!! – Bravo Mar 03 '22 at 12:46