Skip to content
Advertisement

Memoize a recursive Fibonacci function

I created a withMemo function that returns a memoized version of the provided function.

JavaScript

How can I memoize this fibonacci function that works with recursion ?

JavaScript

Indeed withMemo(fibo) doesn’t improve performance since the recursive calls inside fibo still point to the unmemoized version…

So I have to alter the declaration of fibo to make momoization work:

JavaScript

Is there a way to memoize fibo (or any other recursive function for that matter) without altering it’s declaration in the way I did ?

Advertisement

Answer

You can use let fibo instead of const fibo. Then replace the fibo variable with a memoized version. By updating fibo the nested call will now refer to the memoized fibo function instead of the original.

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement