Currently, I was able to get the following function to retreive the max value from an array through recursion
const max = ([a,...rest]) => !rest.length || a > max(rest) ? a : max(rest);
console.log(max([-3,3,19,61,99,22,55])); // 99
console.log(max([32,0,9,87,73])); // 87
console.log(max([1,6,8])); // 8
However, when I try to refactor it with an extra parameter "b" through destructuring, the whole function just won't work properly anymore.
const max = ([a,b,...rest]) => !rest.length || a > b ? a : max([b,...rest]);
console.log(max([-3,3,19,61,99,22,55])); // 99
console.log(max([32,0,9,87,73])); // 32
console.log(max([1,6,8])); // 6
Can someone kindly explain what I am doing wrong or point me in the right direction. I am new to recursion and programming so any help will be greatly appreciated :)
UPDATE:
Took me awhile to figure it out, but here is the recursive solution with destructuring:
const max = ([a,b,...rest]) => !rest.length && !b ? a : max([b < a ? a : b,...rest]);
- if the length of "rest" is equal to "0" and "b" doesn't exists then return "a"
!rest.length && !b ? a
- else, invoke "max" recursively
: max([b < a ? a : b,...rest]);
- for the 1st argument, if "b is less than "a" then return "a" else return "b"
- for the 2nd argument, we'll simply "spread" in "rest"
awhen!rest.lengthis true (ie:aandbare the only elements left in your array), butbmight be larger thanain this case. Also, you are returningaifa > b, and then don't do any more recursive calls, so for[32, 0, ...], the32is bigger than0, so you straight away return32without checking the rest of the arraya > max(rest). So it will recursively compare all. But in the second case comparison is between just a and ba > b. So, whenever such a case occurs code execution will finish. In 2nd method, 1st example99 > 22first case whena > band hence luckily right answer, 2nd example32 > 0(a > b)found in 1st comparison only and hence wrong answer, 3rd example in 2nd loop params are[6, 8, ...[]]and hence due torest.lengthcheck 6 is returned and comparison isn't even done as length check is done first.