0

This is a solution to a toy problem in Javascript. The job was to find a Palindrome(word that you can read the same back and forth, like "radar", "rotor") in a string with words separated by spaces or return an empty string if no word fits the requirement. i understand everything but i don´t know how they use the reduce method to find the word, especially the syntax " ? word : prevWord"

Could somebody explain??

function reverseString(str) {
  return str.split('').reverse().join('');
}

function isPalindrome(str) {
  return str === reverseString(str);
}

function getWords(str) {
  return str.split(' ');
}

function findPalindrome(str) {
  var words = getWords(str);
  return words.reduce(function(prevWord, word) {
    return isPalindrome(word) ? word : prevWord;
  }, '');
}

As you can see if i use the last function

findPalindrome("this is a very good rotor");

It will return

"rotor"
  • 1
    Possible Duplicate of [How do you use the ? : (conditional) operator in JavaScript?](http://stackoverflow.com/questions/6259982/how-do-you-use-the-conditional-operator-in-javascript) – Tushar Oct 13 '16 at 03:33
  • Check this documentation for `reduce`: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce – Sayan Pal Oct 13 '16 at 03:34
  • Thanks @Tushar so basically as an if / else statement – Ignacio Palma Balboa Oct 13 '16 at 03:54
  • 1
    `return a ? b : c` is the same as `if (a) return b; else return c;` – Mulan Oct 13 '16 at 05:01
  • And `getWords(str).find(isPalindrome)` would solve the problem completely, without the need for `reduce`. Or if you want to find all the palindromes in the sentence, `getWords(str).filter(isPalindrome)`. – Mulan Oct 13 '16 at 05:02

0 Answers0