Skip to content

Instantly share code, notes, and snippets.

@bagaag
Last active March 2, 2017 15:55
Show Gist options
  • Save bagaag/8611619 to your computer and use it in GitHub Desktop.
Save bagaag/8611619 to your computer and use it in GitHub Desktop.
Palindrome Test in JavaScript
// reverse word and compare
function isPalindrome1(word) {
var s = '';
for (var i=word.length-1; i>=0; i--) {
s += word[i];
}
return s === word;
}
// compare from end to end (more efficient)
function isPalindrome2(word) {
for (var a=0; a<word.length; a++) {
var b = word.length-1 - a;
if (a===b || b<a) return true;
else if (word[a]!=word[b]) return false;
}
}
test(isPalindrome1);
test(isPalindrome2);
function test(fn) {
console.log('mom: ' + fn('mom'));
console.log('racecar: ' + fn('racecar'));
console.log('kook: ' + fn('kook'));
console.log('family: ' + fn('family'));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment