Last active
December 13, 2020 13:18
-
-
Save arcdev1/1162e82f81bf681de1062ca361cc2c2f to your computer and use it in GitHub Desktop.
This file contains hidden or 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 whether or not a given string is a Palindrome | |
* @param {string} stringToTest - the string to test. | |
*/ | |
function isPalindrome(stringToTest) { | |
if (typeof stringToTest !== "string") { | |
throw new TypeError("isPalindrome() expected a string, but got " + | |
Object.prototype.toString.call(stringToTest) + " instead!"); | |
} | |
var normalizedString = stringToTest | |
.toLowerCase() | |
.replace(/\W/g, ''); // remove non-word characters | |
if (normalizedString.length === 0) { | |
return true; // an empty string is a palindrome. | |
} | |
return normalizedString === normalizedString.split('').reverse().join(''); | |
} | |
// tests (should be in a separate 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 + warn"); | |
console.log(isPalindrome(" ") + " = true + warn"); | |
console.log(isPalindrome("1221") + " = true"); | |
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)); // blow up | |
console.log(isPalindrome(undefined)); // blow up | |
console.log(isPalindrome(null)); // blow up |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment