Skip to content

Commit f17ef16

Browse files
author
Connor Leech
committed
add palindromes
1 parent 25027bd commit f17ef16

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
// --- Directions
2+
// Given a string, return true if the string is a palindrome
3+
// or false if it is not. Palindromes are strings that
4+
// form the same word if it is reversed. *Do* include spaces
5+
// and punctuation in determining if the string is a palindrome.
6+
// --- Examples:
7+
// palindrome("abba") === true
8+
// palindrome("abcdefg") === false
9+
10+
function palindrome(str){
11+
const middle = Math.floor(str.length/2);
12+
13+
const firsthalf = str.substring(0, middle);
14+
const secondhalf = (str.length % 2 === 0)? str.substring(middle) : str.substring(middle + 1);
15+
16+
return (firsthalf === reverse(secondhalf));
17+
}
18+
19+
function reverse(str){
20+
return str.split('').reduce((accum, letter)=> letter + accum, '');
21+
}
22+
23+
24+
// first solution. No need for splitting the terms into halves!
25+
function palindromeSolution1(str){
26+
const reversed = str.split('').reduce((accum, letter)=> letter + accum, '');
27+
return reversed === str;
28+
}
29+
30+
31+
// second solution: compare each letter from beginning and end of array
32+
function palindromeSolution2(str){
33+
return str.split('').every((current, index, arr)=>{
34+
return (current === arr[arr.length - index - 1]);
35+
});
36+
}
37+
38+
console.log(palindromeSolution2("abba"));
39+
console.log(palindromeSolution2("abcdefg"));

0 commit comments

Comments
 (0)