Skip to content

Commit

Permalink
add: isPalindrome function implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
EliasAfara committed Oct 15, 2023
1 parent 5bf6480 commit 829fce8
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 0 deletions.
3 changes: 3 additions & 0 deletions DIRECTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,6 @@
- [QuickSort](Sorting/QuickSort.js)
- [SelectionSort](Sorting/SelectionSort.js)
- [ThreeNumberSort](Sorting/ThreeNumberSort.js)

- **Strings**
- [PalindromeCheck](Strings/PalindromeCheck.js)
25 changes: 25 additions & 0 deletions Strings/PalindromeCheck.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/**
* Check if a given string is a palindrome.
*
* @param {string} str - The input string to be checked for palindrome.
* @returns {boolean} - True if the input string is a palindrome, false otherwise.
*
* @description
* A palindrome is a string that reads the same forwards and backwards. This function
* checks whether the input string is a palindrome, ignoring spaces, punctuation, and
* letter casing. It handles single-character strings as palindromes as well.
*
* @complexity
* - Time Complexity: O(n), where n is the length of the input string.
* The function iterates through the string once to check for palindromic properties.
* - Space Complexity: O(1), as the function only uses a constant amount of extra memory.
*/
function isPalindrome(str) {
// Remove non-alphanumeric characters and convert to lowercase
str = str.replace(/[^a-zA-Z0-9]/g, "").toLowerCase();

// Check if the cleaned string is the same when reversed
return str === str.split("").reverse().join("");
}

export { isPalindrome };
31 changes: 31 additions & 0 deletions Strings/tests/PalindromeCheck.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { isPalindrome } from "../PalindromeCheck";

describe("isPalindrome", () => {
it("returns true for a valid palindrome", () => {
expect(isPalindrome("racecar")).toBe(true);
});

it("returns true for a single character", () => {
expect(isPalindrome("a")).toBe(true);
});

it("returns true for an empty string", () => {
expect(isPalindrome("")).toBe(true);
});

it("returns false for a non-palindrome", () => {
expect(isPalindrome("hello")).toBe(false);
});

it("ignores spaces and punctuation", () => {
expect(isPalindrome("A man, a plan, a canal, Panama")).toBe(true);
});

it("handles letter casing", () => {
expect(isPalindrome("RacECar")).toBe(true);
});

it("returns false for a non-palindrome with spaces", () => {
expect(isPalindrome("not a palindrome")).toBe(false);
});
});

0 comments on commit 829fce8

Please sign in to comment.