Skip to content

Instantly share code, notes, and snippets.

Created May 27, 2016 15:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save anonymous/e5ad20f06ba3837c573b1c8a97565ff8 to your computer and use it in GitHub Desktop.
Save anonymous/e5ad20f06ba3837c573b1c8a97565ff8 to your computer and use it in GitHub Desktop.
'use strict'; // avoid ambiguity and sloppy errors
/**
* Tests wether or not a given string is a Palindrome
* @param {string} stringToTest - the string to test.
*/
function isPalindrome(stringToTest) {
var start = 0,
end,
firstChar,
lastChar,
valid;
// make sure we have a string.
if (typeof stringToTest !== "string") {
// throw if we didn't get a string
throw new TypeError("isPalindrome() expected a string, but got " +
Object.prototype.toString.call(stringToTest) + " instead!");
}
if (/^[^a-z0–9]*$/i.test(stringToTest)) {
// warn if we have no valid characters to test
console.log("No valid characters to test, treated as empty string" +
"\nStack: \n" + new Error().stack);
return true; // an empty string is a palindrome.
}
end = stringToTest.length - 1;
// compare characters from outside in. stop when we get to the middle.
while (start < end) {
firstChar = stringToTest[start].toLowerCase();
lastChar = stringToTest[end].toLowerCase();
valid = true;
if (/[^a-z0-9]/.test(firstChar)) {
start++;
valid =false;
}
if (/[^a-z0-9]/.test(lastChar)) {
end--;
valid=false;
}
if(valid) {
if(firstChar === lastChar) {
start++;
end--;
} else {
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