Reputation: 571
function palindrome(str) {
str = str.toLowerCase().replace(/\W/g,'');
var subStr = str.split(""),newStr = '',anotherStr = '';
for (var j = 0; j < subStr.length;j++){
if(subStr[j] === "_"){continue;}else{anotherStr += subStr[j];}}
for (var i = subStr.length - 1; i > -1;i--){
if(subStr[i] === "_"){continue;}else{newStr += subStr[i];}}
if (anotherStr === newStr) {
return true;
} else {
return false;
}
}
Can someone please help me in compressing this code? It worked fine, but I believe the block of codes could be reduced.
Thanks.
Upvotes: 1
Views: 52
Reputation: 92854
A Palindrome is a word, phrase, number, or other sequence of characters which reads the same backward or forward.
Short solution using Array.some
and Array.reverse
functions:
function palindrome(str) {
str = str.toLowerCase().replace(/\W/g,'');
var forward = str.split(""), backward = forward.concat().reverse();
return !forward.some((v, k) => v !== backward[k]);
}
console.log(palindrome("Animal loots foliated detail of stool lamina")); // true
console.log(palindrome("not palindrome at all")); // false
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some
Upvotes: 1
Reputation: 47099
A simple for loop until you have checked half the string should do:
This will compare first, with last, second with second to last, ... all the way until you reaches the middle of the string, in which case it will stop the loop and return true if no error was found. If an error is found it will return false immediately.
function palindrome(val) {
// If you only want to compare a-zA-Z0-9:
// val = val.replace(/[\W_]/g, '');
for(var i = 0; i < val.length/2; i++) {
if (val[i] != val[val.length - 1 - i]) {
return false;
}
}
return true;
};
The super naive approch is to use:
function palindrome(val) {
val = val.replace(/\W_/g, '');
return val === val.split('').reverse().join('');
}
Upvotes: 2
Reputation: 791
You can do it without any loops. Just reverse the string a compare them.
function palindrome(str) {
str = str.toLowerCase().replace(/\W/g,'');
reverse = str.split('').reverse().join('');
return str === reverse;
}
Upvotes: 1
Reputation: 6723
There is something called a JS minifier which takes JavaScript code and compresses it so save memory. You can use this site to do so: http://javascript-minifier.com/
And here is the output of your code compresses:
function palindrome(r){r=r.toLowerCase().replace(/\W/g,"");for(var e=r.split(""),n="",o="",t=0;t<e.length;t++)"_"!==e[t]&&(o+=e[t]);for(var a=e.length-1;a>-1;a--)"_"!==e[a]&&(n+=e[a]);return o===n?!0:!1}
Upvotes: 0