Given a string, return true if the string is a palindrome or false if it is not. Palindromes are strings that form the same word if it is reversed. Include spaces and punctuation in determining if the string is a palindrome
palindrome('level') // returns true
palindrome('abcde') // reutrns false
palindrome('Learning To Code!') // returns false
palindrome('hi ih') //returns true
Solution 1 - built in functions and compare
- Reverse the given string
- Compare new reversed string to original string
- Return true if string is equal else return false
const palindrome = (str) => {
return str === str.split('').reverse().join('')
}
Solution 2- Advanced array helper
- Split the string into a array
- Using the .every array function loop through each character
- Check each character (starting from the left/beginning) against its counterpart (starting from the right/end) to see if the characters are equal, continuing sequentially until complete. In the case of odd numbered arrays, this will result in the middle character comparing to itself.
- If all characters are equal return true, else return false.
const palindromeCompare = (str) => {
return str.split('').every((char, i) => {
return char === str[str.length - i - 1]
})
}
This approach is not as efficient as the first, as it does twice the amount of comparisons that it needs to.
ย