-
-
Save VasilSlavchev/ca9c87e8fce08c3f6aa4f2eaffad6575 to your computer and use it in GitHub Desktop.
Palindrome Test in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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