Skip to content

Instantly share code, notes, and snippets.

@alex-hladun
Created May 26, 2020 21:13
Show Gist options
  • Save alex-hladun/da6c0828a05fac38969fa3d0c6973f95 to your computer and use it in GitHub Desktop.
Save alex-hladun/da6c0828a05fac38969fa3d0c6973f95 to your computer and use it in GitHub Desktop.
Checks whether a string is a palindrome or not.
// FUNCTION IMPLEMENTATION (MULTIPLE BUGS)
const isPalindrome = function(str) {
const noSpaces = str.split(" ").join("");
console.log(noSpaces);
const midIndex = Math.floor(noSpaces.length/2);
const lastIndex = noSpaces.length - 1;
for (let i = 0; i < midIndex; i++) {
// console.log(str[i])
// console.log(str[lastIndex - i])
if (noSpaces[i].toLowerCase() !== noSpaces[lastIndex - i].toLowerCase()) return false;
}
return true;
};
// Assertion Function
const assertPalindrome = function(word, expected) {
console.log(`Testing isPalindrome(\"${word}\"):`);
const actual = isPalindrome(word);
if (actual === expected) {
console.log("\x1b[32m%s\x1b[0m", `\tPASS ✅ function returned ${actual}\n`);
} else {
console.log("\x1b[31m%s\x1b[0m", `\tFAIL 🛑 function returned ${actual} (expected ${expected})\n`);
}
}
// TEST CODE
// These should all pass assertion, but they don't.
assertPalindrome('p', true);
assertPalindrome('racecar', true);
assertPalindrome('my gym', true);
assertPalindrome('foo', false);
assertPalindrome('fluff', false);
assertPalindrome('just some random words', false);
assertPalindrome('rise to vote sir', true);
assertPalindrome('rise to vote sirs', false);
assertPalindrome('a man a plan a canal panama', true);
// Bonus / Stretch: Uncomment these tests and figure out why these are also failing
assertPalindrome('Kayak', true);
assertPalindrome('a santa at NASA', true);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment