recursive functions with memoization caching example issue
danieluhl opened this issue · 7 comments
danieluhl commented
@loverajoel Either I'm entirely missing something or this first example doesn't do anything:
https://github.com/loverajoel/jstips/blob/gh-pages/_posts/en/2016-01-29-speed-up-recursive-functions-with-memoization.md
var fibonacci = (function(){
var cache = {
0: 0,
1: 1
};
return function(n){
return n <= 1 ? cache[n] : (cache[n] = cache[n-1] + cache[n-2]);
}
})()
I think what this might be going for is something like this?
var fibonacci = (function() {
cache = {
'0': 0,
'1': 1
};
function f(n) {
var result;
if (n in cache) {
result = cache[n];
} else {
result = f(n - 2) + f(n - 1);
cache[n] = result;
}
return result;
}
return f;
})();
loverajoel commented
@hingsir ping
mrosata commented
@danieluhl true
RafaelTaranto commented
Yep, the first example only works if you go sequentially starting at 2.
ffigiel commented
This will be fixed in es9.
jk, thanks for pointing this out 👍
loverajoel commented
@danieluhl PR merged, can I close this?
RafaelTaranto commented
Still not getting result from cache, can't submit pr right now but the return should be :
return (n in cache) ? cache[n] : (cache[n] = self(n-1) + self(n-2));