Skip to content

Commit 55fe590

Browse files
committed
re-write palindrome algorithmn
1 parent 8a5dedd commit 55fe590

3 files changed

Lines changed: 49 additions & 26 deletions

File tree

palindrome/palindrome.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
function isPalindromeRecursive(chars, s, e) {
2+
if (s === e) {
3+
return true;
4+
}
5+
6+
if (chars[s] !== chars[e]) {
7+
return false;
8+
}
9+
10+
if (s < e + 1) {
11+
return isPalindromeRecursive(chars, s + 1, e - 1)
12+
}
13+
14+
return true;
15+
}
16+
17+
function isPalindrome(s) {
18+
// convert the input to string
19+
const chars = String(s);
20+
const len = chars.length
21+
if (len <= 1) {
22+
return true
23+
}
24+
return isPalindromeRecursive(chars, 0, len - 1);
25+
}
26+
27+
module.exports = isPalindrome;

palindrome/palindrome.test.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
const isPalindrome = require('./palindrome');
2+
3+
describe('isPalindrome()', () => {
4+
it('should return true for single number', () => {
5+
expect(isPalindrome(1)).toBeTruthy();
6+
})
7+
8+
it('should return true for valid number "121"', () => {
9+
expect(isPalindrome(121)).toBeTruthy();
10+
})
11+
12+
it('should return true for same number 111', () => {
13+
expect(isPalindrome(111)).toBeTruthy();
14+
})
15+
it('should return false for invalid number', () => {
16+
expect(isPalindrome(123)).toBeFalsy();
17+
})
18+
19+
it('should return true for long value', () => {
20+
expect(isPalindrome(123321123321)).toBeTruthy();
21+
})
22+
})

src/palindrome.js

Lines changed: 0 additions & 26 deletions
This file was deleted.

0 commit comments

Comments
 (0)