Skip to content

Commit d58763b

Browse files
Merge pull request akshitagit#99 from NoRoboto/string/palindrome
Add palindrome string algorithm using for loop (classical approach)
2 parents a001cc8 + 5957563 commit d58763b

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

Strings/palindrome.js

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
2+
/*
3+
Classical palindrome js version.
4+
"A palindrome is a word, number, phrase, or other sequence of
5+
characters which reads the same backward as forward, such as madam, racecar."
6+
https://en.wikipedia.org/wiki/Palindrome
7+
*/
8+
9+
/**
10+
* Returns if the string is palindrome or not
11+
* case sensitive
12+
* @param {string} string. Required
13+
* @returns {boolean}
14+
*/
15+
function isPalindrome(string) {
16+
const stringLength = string.length;
17+
18+
if (stringLength <= 1) return true;
19+
20+
for (let index = 0; index < stringLength / 2; index++) {
21+
if (string[index] !== string[stringLength - 1 - index]) {
22+
return false;
23+
}
24+
}
25+
26+
return true;
27+
}
28+
29+
function isPalindromeTest() {
30+
const stringList = ['', 'hi', 'ANA', 'racecar'];
31+
32+
for (string of stringList) {
33+
console.assert(isPalindrome(string), 'Ups! %s is not palindrome :/', string);
34+
}
35+
}

0 commit comments

Comments
 (0)