From ec86d926bb5e169ff27c1dba2f13614496ce05c4 Mon Sep 17 00:00:00 2001 From: Chris Newell <84216346+ChrisNewelldev@users.noreply.github.com> Date: Sun, 18 Jan 2026 14:01:01 +0800 Subject: [PATCH] feat: add palindrome utility with tests --- .gitignore | 2 ++ package-lock.json | 2 +- src/utils/palindrome.js | 22 ++++++++++++++++++++++ test/utils/palindrome.spec.js | 23 +++++++++++++++++++++++ 4 files changed, 48 insertions(+), 1 deletion(-) create mode 100644 .gitignore create mode 100644 src/utils/palindrome.js create mode 100644 test/utils/palindrome.spec.js diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2752eb9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +node_modules/ +.DS_Store diff --git a/package-lock.json b/package-lock.json index 8fce75c..8e2718d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -7,7 +7,7 @@ "": { "name": "nodejs-practice-repository", "version": "1.0.0", - "license": "ISC", + "license": "MIT", "devDependencies": { "jest": "^29.7.0" } diff --git a/src/utils/palindrome.js b/src/utils/palindrome.js new file mode 100644 index 0000000..d1c5855 --- /dev/null +++ b/src/utils/palindrome.js @@ -0,0 +1,22 @@ +/** + * Author: Chris Newell + * Date: 18 January 2026 + * File: palindrome.js + * Description: This script checks whether a string is a palindrome + */ +'use strict'; + +// The isPalindrome function checks if a string reads the same forward and backward +function isPalindrome(str) { + if (typeof str !== 'string') { + throw new Error('Input must be a string'); + } + + // Normalize: lowercase and remove non-alphanumeric characters + const normalized = str.toLowerCase().replace(/[^a-z0-9]/g, ''); + const reversed = normalized.split('').reverse().join(''); + + return normalized === reversed; +} + +module.exports = { isPalindrome }; \ No newline at end of file diff --git a/test/utils/palindrome.spec.js b/test/utils/palindrome.spec.js new file mode 100644 index 0000000..e7157d8 --- /dev/null +++ b/test/utils/palindrome.spec.js @@ -0,0 +1,23 @@ +/** + * Author: Chris Newell + * Date: 18 January 2026 + * File: palindrome.spec.js + * Description: This script tests the isPalindrome function. + */ +'use strict'; + +const { isPalindrome } = require('../../src/utils/palindrome'); + +describe('palindrome.js', () => { + it('should return true for a simple palindrome', () => { + expect(isPalindrome('racecar')).toBe(true); + }); + + it('should ignore case and non-alphanumeric characters', () => { + expect(isPalindrome('A man, a plan, a canal: Panama')).toBe(true); + }); + + it('should return false when the string is not a palindrome', () => { + expect(isPalindrome('hello')).toBe(false); + }); +}); \ No newline at end of file