I've read all the documentation on recursive functions and Math.max but I still don't quite understand how this function works. Can someone explain what's happening here step by step? In particular, the second return statement involving Math.max().
function findLongestWordLength(str) {
// split the string into individual words
const words = str.split(" ");
// words only has 1 element left that is the longest element
if (words.length == 1) {
return words[0].length;
}
// if words has multiple elements, remove the first element
// and recursively call the function
return Math.max(
words[0].length,
findLongestWordLength(words.slice(1).join(' '))
);
}
console.log(findLongestWordLength("The quick brown fox jumped over the lazy dog"));
Why would someone write something so terrible!
Let's look at "hello goodbye all"
This code is saying:
The idea of breaking the string into words, and then putting all the words except the first back into a string just so you can call yourself recursively is pretty bizarre.
So a typical run looks like:
findLongestWordLength('hello goodbye all')
= max(5, findLongestWordLength('goodbye all'))
= max(5, max(7, findLongestWordLength('all')))
= max(5, max(7, 3))
= max(5, 7)
= 7
Note that this is the standard trick of recursion. You prove the code works by assuming that it works on everything that is shorter.
Obviously this code works on all strings with one word in it. And given a string with n > 1 words in it, you assume that you're going to get the right answer when you call it with a string with n - 1 words in it, and then use that to get the right answer for your current string.