- Published on
Palindromes - JavaScript Algorithms
- Authors
- Name
- Curtis Warcup
A palindrome is a word, phrase, number, or sequence of words that reads the same backward as forward. An example of a palindrome is "madam", which reads as "madam" backwards. Sentences can be palindromes as well. For example: "taco cat" and "red rum, sir, is murder".
Example were we want to include spaces and punctuation in determining if the string is a palindrome.
palindrome('abba') // true
palindrome('abcdefg !') // false
Methods
Direct Comparison with Reverse
function palindrome(str) {
let newStr = str.split('').reverse().join('')
return str === newStr
}
Every() method
Can use the every
method to check if every element in the array is true.
every((element, index, array) => {
/* ... */
})
The every() method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.
const array = [1, 30, 39, 29, 10, 13]
array.every((value) => value < 40) // true, because all values in the array are less than 40.
We could use every()
to check if every element in the array is true. However, the downside if you are doing a lot of extra comparisons. You only NEED to compare until you get halfway through the array.
function palindrome(str) {
return str.split('').every((character, index) => {
return character === str[str.length - index - 1]
})
}
With Spead Operator
const palindrome = (str) => {
const s = str.toLowerCase().replace(/[\W_]/g, '')
return s === [...s].reverse().join('')
}