Three ways to check for palindromes in JavaScript
Toni Domazet
Posted on September 11, 2018
A palindrome is a word or a phrase that is the same whether you read it backward or forwards, for example, the word 'level'.
I'm going to create three different functions that are doing the same job - palindrome check for a passed string. I will mesure time of function execution to see which one of this function gives the best performance using performance.now() Web API method.
Create an array
isPalindrome = (string) => {
string = string.toLocaleLowerCase();
return Array.from(string).toString() === Array.from(string).reverse().toString()
}
//0.52 ms
Array object has a lot of useful methods - one of them is reverse(), but first, we need to create an Array from a string. After reverse, the first array element becomes the last, and the last array element becomes the first. We can't do check now, because condition will always be false as they're objects with different locations in memory. toString() method will return a string from our arrays.
Recursion
isPalindrome = (string) => {
let strLen = string.length;
string = string.toLocaleLowerCase();
if (strLen === 0 || strLen === 1) {
return true;
}
if (string[0] === string[strLen - 1]) {
return isPalindrome(string.slice(1, strLen - 1) );
}
return false;
};
//0.30 ms
Recursion is a process when a function calls itself to solve a problem. In our code, function is called until string completes (empty string or one char left), or if condition falls. First check for first and last char in the string, then if they are same do the same thing for a substring with first and last char removed, and so on...
for - loop
isPalindrome = (string) => {
let strLen = Math.floor(string.length / 2);
string = string.toLocaleLowerCase();
for (let i = 0; i < strLen; i++) {
if (string[i] !== string[strLen - i - 1]) {
return false;
}
}
return true;
}
//0.20 ms
for loop starts with the check for first char of the string and last char of the string. If it's equal, continue iterating through the string until the string reaches the center.
I like the first approach as it's clean and simple, but from a performance view, it gives us the worst result, where simple for loop is more than twice time faster.
Posted on September 11, 2018
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.