Reputation: 73
I don't understand the last steps in the memoization design pattern. This is my code with classic fibonacci calculation:
//Memoization
const fiboCache = () => {
const cache = [0,1];
const fibo = (x) => {
let result = cache[x];
if(typeof result !== 'number') {
console.log('new calculation for: ' + x);
result = fibo(x-1) + fibo(x-2);
cache[x] = result;
}
return result;
};
return fibo;
};
const getFibo = fiboCache();
console.log(getFibo(4));
The problem for me is the last step, I tried to break it down each iteration which looks like this:
4. result=undef; console.log; result=3; cache=[0,1,empty,empty,3]
3. result=undef; console.log; result=2; cache=[0,1,empty,2,3]
2. result=undef; console.log; result=1; cache=[0,1,1,2,3]
1. result=1; return 1;
I understand how the array is working as cache for my next calculations, but as soon as I'm on the last iteration (1) my result
object becomes 1 which is breaking my recursion, and I'm going straight to return result
.
Doesn't that mean I'm just returning 1
at the end? Shouldn't I return here the last item of my array?
Upvotes: 0
Views: 59
Reputation: 34408
It's not quite that simple: you'll have to work up and down the recursion levels as each one returns. It'll go something like this
i.e.
It may also be instructive to step through this with a debugger and watch the cache contents and the call stack.
Upvotes: 1