DEV Community

Discussion on: How to Validate a Palindrome

Collapse
 
arekx profile image
Aleksandar Panic • Edited

Here is a bit of a shorter and optimized version of it.

Also few more things:

  • There is no need to go from 0 to string.length - 1. You only need to go to a half of the string because you are checking from the both sides, they will meet in half.
  • Also alphanumeric check is a bit too much to do per character since you can just transform the whole string into data you want to to use beforehand.
  • There is no need for left / right variables because you can always calculate them as left = string[currentIndex] and right = string[lastIndex - currentIndex]
function isPalindrome(str) {
    str = str ? str.toLowerCase().replace(/[^a-zA-Z0-9]/g, '') : "";
    const maxHalf = str.length / 2;
    const lastIndex = str.length - 1;

    for (let currentIndex = 0; currentIndex < maxHalf; currentIndex++) {
        if (str[currentIndex] !== str[lastIndex - currentIndex]) {
            return false;
        }
    }

    return true;
}

Also some line explanations:

  • Line str = str ? str.toLowerCase().replace(/[^a-zA-Z0-9]/g, '') : ""; does some validation checks and handles lowercase and non-alphanumeric characters.
  • Lines const maxHalf = str.length / 2; and const lastIndex = str.length - 1; are mostly for optimization so that the for doesn't calculate them again during each iteration