loverajoel/jstips

recursive functions with memoization caching example issue

danieluhl opened this issue · 7 comments

@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;
})();

Yep, the first example only works if you go sequentially starting at 2.

This will be fixed in es9.
jk, thanks for pointing this out 👍

my bad, pr196 may fix that

@danieluhl PR merged, can I close this?

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));