0

High performance palindrome check

Function JavaScript 1 revisions 316 8 days ago 8 days ago
const badCharacters = /[^a-z\d]/g;

const palindrome = (str) => {
    let i = 0;
    const max = ~~((str = str.toLowerCase().replace(badCharacters, "")).length / 2 + 1);
    while (i !== max) {
        if (str[i] !== str[str.length - ++i]) {
            return false;
        }
    }
    return true;
};

This function, while looking not pretty, is a very fast function for checking palindromes. Check this benchmark for a comparison.

badCharacters are for characters to be ignored entirely (as if they never existed in the string at all).