DEV Community

Javascript Algorithms #2: Palindromes

Philip Obosi on August 01, 2018

Palindromes! Palindromes!! Palindromes!!! Ooooh boy. I'm pretty sure that by now you are wondering what these are. You know personally as a softwa...
Collapse
 
kepta profile image
Kushan Joshi • Edited

Great explanation Justine, especially using the .each API. Since javascript is so versatile, I am adding one more solution which uses iterator from my previous article dev.to/kepta/how-i-learned-to-stop...

function isPalindrome(str) {
   const iter = [...str.toLowerCase()];
   for (let char of iter) {
      if (char !== iter.pop()) { return false}
   }
   return true
}

The good thing about this is that it iterates only over half of the string to check if it is palindrome.

Collapse
 
luc_tuyishime profile image
jean luc tuyishime

Do you have an idea on how you can do permutation of palindrome??

Collapse
 
itsjzt profile image
Saurabh Sharma

those memories of solving algorithms at freecodecamp.org

const isPalindrome = str => str.toLowerCase() === str.toLowerCase().split().reverse().join() 

Collapse
 
mhmoodlan profile image
Mahmoud Aslan

nice, somehow didn't work until i added the splitters for split() and join()

const isPalindrome = str => str.toLowerCase() === str.split('').reverse().join('')
Collapse
 
itsjzt profile image
Saurabh Sharma

thats why we needs unit tests 😅

Collapse
 
worldclassdev profile image
Philip Obosi • Edited

Thanks for the save. I didn't even look at the syntax closely. It's still a pretty concise solution though

Collapse
 
worldclassdev profile image
Philip Obosi

Clean and concise

Collapse
 
styvensoft profile image
Steveen Echeverri

Palindrome example for a word, phrase, number or sequence of characters:

const isPalindrome = str => [...`${str}`].reverse().join('') == str;
Collapse
 
kenthmordecai profile image
Kenthmordecai

Great!