Skip to content

Instantly share code, notes, and snippets.

@VasilSlavchev
Forked from bagaag/palindrome.js
Created March 2, 2017 15:55
Show Gist options
  • Save VasilSlavchev/ca9c87e8fce08c3f6aa4f2eaffad6575 to your computer and use it in GitHub Desktop.
Save VasilSlavchev/ca9c87e8fce08c3f6aa4f2eaffad6575 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