JavaScript Algorithms and Data Structures - Missing Letter

Did the challenge before reading the hints and ended up coming up with a solution that didn’t make use of CharCode or for loops, is this a good way of doing it?

  const alphabet = "abcdefghijklmnopqrstuvwxyz";
  if (str === alphabet) {
    return undefined;
  }
  const reg = new RegExp(`[${str}]`, 'gi');
  
  const returnStr = alphabet
    .substring(alphabet.indexOf(str[0]), alphabet.indexOf(str[str.length-1]))
    .replace(reg, "");

  console.log(reg, returnStr, alphabet.indexOf(str[0]), str[str.length-1])
  return returnStr;
}

fearNotLetter("abce");
fearNotLetter("stvwx");
fearNotLetter("abcdefghijklmnopqrstuvwxyz");

Your code is incomplete. And a link to the challenge would be very helpful.

what do you mean by my code is incomplete?

He means you have not posted all the code. Where is the function definition for eg?

Yes, like hbar1st said.

That being said, if I assume that the only line you are missing is the function declaration…

Is it a good solution? Sure. It works. Be proud of that.

Is it the best solution? I don’t know. One weakness of yours is that it is a little arcane. But I would say the same about the offered solutions, especially the second one.

Personally, I like solutions that are very clear and easy to read. This is what I came up with:

const fearNotLetter = str => {
  const chars = str.split('')

  for (let i = 1; i < chars.length; i++) {
    const expectedCode = chars[i - 1].charCodeAt(0) + 1
    const actualCode = chars[i].charCodeAt(0)

    if (actualCode !== expectedCode) {
      return String.fromCharCode(expectedCode)
    }
  }

  return undefined
}

Is it better than yours or the other solutions? To me, a bit. But again, I prioritize readability. The code is telling a story, it is telling me what it is doing. I could have made this “simpler”:

const fearNotLetter = str => {
  const chars = str.split('')
  for (let i = 1; i < chars.length; i++) {
    if (chars[i - 1].charCodeAt(0) + 1 !== chars[i].charCodeAt(0)) {
      return String.fromCharCode(chars[i - 1].charCodeAt(0) + 1)
    }
  }
}

Sure, that has fewer lines and doesn’t create a few variables. But it’s harder to look at it and know what it is doing. Good code tells you what it is doing. And if you have to read 3k lines of code to find a bug, every 1/10 of a second matters. And if other coders understand your code, then it is less likely that they will make mistakes while maintaining it.

If you become a professional developer, I think you’ll find that those are very important things.

But your solution is good. It works. Be proud of that. Just think about some of the things about which I spoke.