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"