Last active
October 13, 2015 16:49
-
-
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
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
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