Reputation:
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
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