-
-
Save binoculars/2eb8f9a34796d83c62783ff7d4a226a6 to your computer and use it in GitHub Desktop.
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
'use strict'; // avoid ambiguity and sloppy errors | |
/** | |
* Tests wether or not a given string is a Palindrome | |
* @param {string} stringToTest - the string to test. | |
* @returns {boolean} | |
*/ | |
function isPalindrome(stringToTest) { | |
var start = 0; | |
// make sure we have a string. | |
if (typeof stringToTest !== "string") | |
return false; | |
stringToTest = stringToTest | |
.toLowerCase() | |
.replace(/\W+/g, ''); | |
var end = stringToTest.length - 1; | |
// compare characters from outside in. stop when we get to the middle. | |
while (start < end) { | |
if (stringToTest[start++] !== stringToTest[end--]) | |
return false; | |
} | |
// if we get here, it's a palindrome | |
return true; | |
} | |
// tests (should be in a seperate file using a test framework) | |
console.log(isPalindrome("something that is not a palindrome") + " = false"); | |
console.log(isPalindrome("something that is \n not a palindrome") + " = false"); | |
console.log(isPalindrome("race \n car") + " = true"); | |
console.log(isPalindrome("") + " = true"); | |
console.log(isPalindrome(" ") + " = true"); | |
console.log(isPalindrome("1221") + " = true 1221"); | |
console.log(isPalindrome("0") + " = true"); | |
console.log(isPalindrome("racecar") + " = true"); | |
console.log(isPalindrome("No 'x' in Nixon!") + " = true"); | |
console.log(isPalindrome("~~!~!~") + " = true + warn"); | |
console.log(isPalindrome("Momsie") + " = false"); | |
console.log(isPalindrome(12) + " = warn + false"); | |
console.log(isPalindrome(undefined) + " = warn + false"); | |
console.log(isPalindrome(null) + " = warn + false null"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment