I completed this exercise from Free Code Camp today. In essence, it’s palindrome checker that will return TRUE
if a word or a phrase is a palindrome (minus all numbers and special characters), or FALSE
if it’s not a palindrome.
I applied all the recent Javascript lessons I have revisited recently to check if a phrase is palindromic in Javascript while trying to keep the solution as short as possible.
Here is one solution:
function palindrome(str) {
str = str.replace(/[^a-zA-Z0-9]+/g, "")
.toLowerCase(); // strip to only lower case alphabets
const reversed = str
.split("") // make into an array of characters
.reverse() // reverse the array
.join(""); // create a new string from the reversed array
return str == reversed ? true : false; // compare the two
}
Firstly, the function receives a string that gets stripped of non-alphabet characters and transformed into an all lower case string with no space.
The new string is then broken down into an array of chars
that will undergo an array reversal before being reformed into a new string, called reversed
.
The final piece of the code is to compare the original parameter str
(stripped) against reversed
, which will return either TRUE
or FALSE
.
I also wrote some unit tests using Jest. Here is the test file:
const palindrome = require("./palindrome");
test("eye", () => {
expect(palindrome("eye")).toBe(true);
});
test("_eye", () => {
expect(palindrome("_eye")).toBe(true);
});
test("race car", () => {
expect(palindrome("race car")).toBe(true);
});
test("not a palindrome", () => {
expect(palindrome("not a palindrome")).toBe(false);
});
test("A man, a plan, a canal. Panama", () => {
expect(palindrome("A man, a plan, a canal. Panama")).toBe(true);
});
test("ever odd or even", () => {
expect(palindrome("ever odd or even")).toBe(false);
});
test("nope", () => {
expect(palindrome("nope")).toBe(false);
});
test("almostomla", () => {
expect(palindrome("almostomla")).toBe(false);
});
test("My age is 0, 0 si ega ym.", () => {
expect(palindrome("My age is 0, 0 si ega ym.")).toBe(true);
});
test("0_0 (: /- :) 0-0", () => {
expect(palindrome("0_0 (: /- :) 0-0")).toBe(true);
});
test("five|_/|four", () => {
expect(palindrome("five|_/|four")).toBe(false);
});