January 2018
Intermediate to advanced
332 pages
7h 36m
English
We can further enhance the generator using memoization, which is a technique of calculating a value only once and remembering it for later:
function memoizedFibonacci(num) { if (num == 0) { memory[num] = 0; return 0; } else if (num == 1 || num == 2) { memory[num] = 1; return 1; } else { if (!memory[num]) { memory[num] = memoizedFibonacci(num - 1) + memoizedFibonacci(num - 2); } return memory[num]; }}
Here, we are relying on an in-memory variable called memory to store and retrieve the previously calculated value of the Fibonacci number within the series, hence avoiding a series of duplicate calculations.
If you log the time taken for each of these methods, you can see that as the size of the input number increases, ...
Read now
Unlock full access