I need to implement such isAlphabet function that will take letters and return true if the order of the letters matches the order in the alphabet, otherwise false:
isAlphabet ('abc') === true
isAlphabet ('aBc') === true
isAlphabet ('abd') === false // - there is c after b
isAlphabet ('a') === true
isAlphabet ('') === false // - task not completed
isAlphabet ('abcdefghjiklmnopqrstuvwxyz') === false // - j goes after i
isAlphabet ('tuvwxyz') === true
isAlphabet ('XYZ') === true
isAlphabet ('mnoprqst') === false // - q goes before r
My code:
function isAlphabet(letters) {
// write code here
const char = letters.toLowerCase();
for (let i = 0; i < char.length; i++) {
if (char[i + 1] - char[i] !== 1) {
return false;
}
}
return true;
}
For input 'abc', the function must return true but my implementation above returns false.
Could you help me to find an error in my code?
Edit
After having changed the code according to some suggestions to ...
function isAlphabet(letters) {
// write code here
const ch = letters.toLowerCase();
for (let i = 0; i < ch.length; i++) {
if (ch[i + 1].charCodeAt() - ch[i].charCodeAt() !== 1) {
return false;
}
}
return true;
}
... the function still errors.
From the above comments ...
The next following (and commented) code example does prove the above claim.