August 2024
Intermediate to advanced
516 pages
11h 47m
English
Thankfully, there’s an easy way to eliminate all these extra recursive calls. We’ll call max only once within our code, and save the result to a variable:
| | function max(array) { |
| | if (array.length === 0) { return null; } |
| | |
| | if (array.length === 1) { return array[0]; } |
| | |
| | // Calculate the max of the remainder of the array |
| | // and store it inside a variable: |
| | const maxOfRemainder = max(array.slice(1)); |
| | |
| | // Comparison of first number against this variable: |
| | if (array[0] > maxOfRemainder) { |
| | return array[0]; |
| | } else { |
| | return maxOfRemainder; |
| | } |
| | } |
By implementing this simple modification, we end up calling max a mere four times. Try it out yourself by adding the console.log(’RECURSION’) ...
Read now
Unlock full access