user2116336
user2116336

Reputation:

Unknown function behavior

I'm trying to understand what this function do, but I'm clueless. Any ideas?

var mystery = function (str) {
    var x=true;
    for(var i=0; i<str.length/2; i++){
        if(str.charAt(i)!=str.charAt(str.length-i-1)){
            x = false;
        }
    }
    return x;
}

Upvotes: 2

Views: 69

Answers (1)

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382464

It simply tests if the string is symmetric, that is has every character at index i equal to the character at the same distance from end of string (at length-i-1) like "radar".

It could be simplified and made faster like this :

var mystery = function (str) {
    for (var i=0; i<str.length/2; i++){
        if (str.charAt(i) !== str.charAt(str.length-i-1)){
            return false;
        }
    }
    return true;
}

And a little faster but less clear :

var mystery = function (str) {
    for (var i=~~(str.length/2); i--;){
        if (str.charAt(i) !== str.charAt(str.length-i-1)){
            return false;
        }
    }
    return true;
}

For the fun, the jspef confirming it : http://jsperf.com/palyndromes

Upvotes: 5

Related Questions