Update palindromes to handle numbers better

The previous solution removed numbers entirely, whereas this one treats
them like letters and checks if they are evenly spaced.

More importantly, the old solution test seemed to check if the numbers
were palindromic, but because the solution replaced them with "", it
wasn't testing what it seemed to.

I added a new test to differentiate between the palindromic "rac3e3car"
and the non-palindromic "r3ace3car".

These changes also obviate the problems raised in Issue #355.
This commit is contained in:
MarLatte 2023-05-20 02:37:41 -04:00
parent 3256f980b0
commit e8fc8ce41e
2 changed files with 4 additions and 1 deletions

View File

@ -1,5 +1,5 @@
const palindromes = function (string) {
const processedString = string.toLowerCase().replace(/[^a-z]/g, "");
const processedString = string.toLowerCase().replace(/[^a-z0-9]/g, "");
return processedString.split("").reverse().join("") == processedString;
};

View File

@ -24,4 +24,7 @@ describe('palindromes', () => {
test('works with numbers in a string', () => {
expect(palindromes('rac3e3car')).toBe(true);
});
test('works with unevenly spaced numbers in a string', () => {
expect(palindromes('r3ace3car')).toBe(false);
});
});