Search code examples
javascriptdryperformancepalindrome

More efficient palindrome code


This is a code I used for the coderbyte challenge "Palindrome". The challenge is to return true if str is the same foward and backward(a palindrome). I got all possible points but I know my code is a little ugly. What would be a more efficient way to write this code. It looks like I am repeating myself and it seems like something that could maybe be written with a for loop.I also see how it could return true when its really false if there was a longer palindrome without the use of a for loop:

function Palindrome(str) { 
    var low=str.toLowerCase()
    var first = low.charAt(0);
    var last = low.charAt(low.length-1);
    var mid = low.charAt(1);
    var mid1 = low.charAt(low.length-2);


       if(first===last)
        if(mid===mid1)


        {
           return true    
        }
            else
        {
            return false    
        }
        else
        {
            return false
        }
        }
print(Palindrome(readline()));           

Solution

  • To check the string if it's a palindrome you just should compare it to its reversed version.
    Say the word hello is not a palndrome because its reversed version olleh is not equal to it. But the word eye is a palindrome same as word abba because they're equal to their reversed versions.

    Code example:

    (function() {
        var reverseStr,
            isPalindrome,
            testStrings;
    
        reverseStr = function(str) {
            var chars = [];
            for(var i = str.length - 1; i > -1; i--) {
                chars.push(str[i]);
            }
            return chars.join('');
        };
    
        isPalindrome = function(str, ignoreCase) {
            if(ignoreCase) {
                str = str.toLowerCase();
            }
            return str === reverseStr(str);
        };
    
        testStrings = ['abba', 'hello', 'eye'];
    
        for(var i = 0, l = testStrings.length; i < l; i++) {
            var word = testStrings[i];
            console.log('Word "%s" is %sa palindrome',
                word,
                isPalindrome(word) ? '' : 'not ');
        }
    })();
    

    DEMO #1

    Another way that could work faster is listed below. Here you don't receive a reversed string to compare but walking towards the middle of the string from its start and its end.

    var isPalindrome = function(str, ignoreCase) {
        var length,
            last,
            halfLength,
            i;
        if(ignoreCase) {
            str = str.toLowerCase();
        }
        length = str.length;
        last = length - 1;
        halfLength = Math.ceil(length / 2);
        for(i = 0; i < halfLength; i++) {
            if(str[i] !== str[last - i]) {
                return false;
            }
        }
        return true;
    };
    

    DEMO #2