DEV Community

Cover image for 'Break'-ing the Palindrome Checker Algorithm
Clark Johnson
Clark Johnson

Posted on

1 2

'Break'-ing the Palindrome Checker Algorithm

In a previous article, I addressed the palindrome algorithm using recursion.

A few days ago, I came across a solution using an iterator to get the job done.
function palindrome2(str) {
    return str
        .split('')
        .every(
            (char, i) => char === str[str.length - 1 - i]
        )
}
Enter fullscreen mode Exit fullscreen mode

This idea utilizes a built-in Javascript iterator 'every', which returns true when a condition is met by every item in the array.

Alt Text

Take the word 'ROTATOR'. It's definitely a palindrome, and we can tell by comparing the first letter to the last letter, then the second letter to the next-to-last letter, and continue until every letter has been tested. If every letter has a match on the opposite side of the word, then we have a palindrome.

The .every function will get the job done. However, we're doing a little too much work. We should be able to stop testing for matching equalities once we reach the halfway point. After that, every check is redundant. Unfortunately, using .every doesn't provide a way to break out of iteration and continue.

Thanks to ES6, we have another solution. Using the for... of construct to iterate gives the option to take advantage of the break keyword.

function palindrome(str) {
    let valid = true;
    const arr = str.split('')
    for (const [i, char] of arr.entries()) {
        if (i > (arr.length / 2))
            break;
        else if (char !== arr[arr.length - i - 1]) {
            valid = false;
            break
        }
    }

    return valid
}
Enter fullscreen mode Exit fullscreen mode

This solution isn't quite as elegant as the first, but it is definitely more efficient. Execution will now cease if either the palindrome test fails on a character or we reach the halfway point. The addition control removes redundancy and reduces the execution time.

More information about for...of is available on MDN.

Happy coding!

Cover Photo by Justin Main on Unsplash

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →