Skip to content

Instantly share code, notes, and snippets.

@ScottKaye
Last active October 13, 2015 16:49
Show Gist options
  • Save ScottKaye/5e5ac0fc6504837e21ed to your computer and use it in GitHub Desktop.
Save ScottKaye/5e5ac0fc6504837e21ed to your computer and use it in GitHub Desktop.
Wanted to make sure I can actually do this. isPalindrome is almost cheating, so isPalindromeAcademic does this problem in a more "classical" way. jsperf: http://jsperf.com/high-level-vs-lower-level-palindrome-test
function normalize(s) {
return s.toLowerCase().replace(/[^a-z]/g, "");
}
Object.defineProperty(String.prototype, "isPalindrome", {
get: function () {
var rev = this.split("").reverse().join("");
return normalize(rev) === normalize(this);
}
});
Object.defineProperty(String.prototype, "isPalindromeAcademic", {
get: function () {
var palindrome = true,
i, to;
(function() {
for (i = 0, to = this.length / 2; i < to; ++i) {
if (this[i] !== this[this.length - i - 1]) {
palindrome = false;
break;
}
}
}).call(normalize(this));
return palindrome;
}
});
console.assert("A man, a plan, a canal, Panama".isPalindrome, "Complex high-level");
console.assert(!"one two three".isPalindrome, "Not-a-palindrome high-level");
console.assert("racecar".isPalindrome, "Easy high-level");
console.assert("racECar".isPalindrome, "Easy 2 high-level");
console.assert("A man, a plan, a canal, Panama".isPalindromeAcademic, "Complex lower-level");
console.assert(!"one two three".isPalindromeAcademic, "Not-a-palindrome lower-level");
console.assert("racecar".isPalindromeAcademic, "Easy lower-level");
console.assert("racECar".isPalindromeAcademic, "Easy 2 lower-level");
console.log("If there are no assertations failed, they all passed!");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment