After some experimentation, I managed to create a function that uses recursion to find the maximum value in an array.
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 attempted to refactor it by adding an extra parameter "b" through destructuring, the function started behaving unexpectedly.
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
If anyone could provide guidance on where I may have gone wrong or point me towards the right solution, I would greatly appreciate it. As a newcomer to recursion and programming, any assistance is valuable :)
UPDATE:
It took some time, but I eventually came up with a modified recursive solution using destructuring:
const max = ([a,b,...rest]) => !rest.length && !b ? a : max([b < a ? a : b,...rest]);
- If the length of "rest" is zero and "b" does not exist, return "a"
!rest.length && !b ? a
- Otherwise, recursively call "max"
: max([b < a ? a : b,...rest]);
- For the first argument, return "a" if "b" is less than "a", otherwise return "b"
- For the second argument, simply spread in "rest"