Skip to content

Commit e6223ca

Browse files
committed
--update: code for palindrome
1 parent 84f0a93 commit e6223ca

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

src/palindrome/index.js

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
function palindromeUsingLoop(str) {
2+
let isPalindrome = true;
3+
let j = str.length - 1;
4+
5+
for (let i = 0; i < str.length / 2; i += 1) {
6+
if (str[i] !== str[j]) {
7+
isPalindrome = false;
8+
break;
9+
}
10+
j -= 1;
11+
}
12+
13+
return isPalindrome;
14+
}
15+
16+
function palindromeUsingEvery(str) {
17+
return str.split('').every((char, index) => char === str[str.length - 1 - index]);
18+
}
19+
20+
module.exports = {
21+
palindromeUsingLoop,
22+
palindromeUsingEvery,
23+
};

src/palindrome/palindrome.test.js

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
const { palindromeUsingLoop, palindromeUsingEvery } = require('.');
2+
3+
describe('Palindrome Strings', () => {
4+
let mirror;
5+
let madam;
6+
7+
beforeEach(() => {
8+
mirror = 'mirror';
9+
madam = 'madam';
10+
});
11+
12+
describe('Using traditional loop', () => {
13+
it('Should return FALSE for `mirror`', () => {
14+
expect(palindromeUsingLoop(mirror)).toBe(false);
15+
});
16+
17+
it('Should return TRUE for `madam`', () => {
18+
expect(palindromeUsingLoop(madam)).toBe(true);
19+
});
20+
});
21+
22+
describe('Using ES6 Array.every', () => {
23+
it('Should return FALSE for `mirror`', () => {
24+
expect(palindromeUsingEvery(mirror)).toBe(false);
25+
});
26+
27+
it('Should return TRUE for `madam`', () => {
28+
expect(palindromeUsingEvery(madam)).toBe(true);
29+
});
30+
});
31+
});

0 commit comments

Comments
 (0)