Skip to content

Instantly share code, notes, and snippets.

@PatrickJS
Last active December 20, 2015 18:48
Show Gist options
  • Select an option

  • Save PatrickJS/6178562 to your computer and use it in GitHub Desktop.

Select an option

Save PatrickJS/6178562 to your computer and use it in GitHub Desktop.
Another method is to memoize the recursive function by extending it with a cache defined inside a closure. This combines the simplicity of the recursive method with the advantages of only calculating each value once.
var fibClosure = (function() {
var cache = [0,1,1];
return function(n) {
if (cache[n] === undefined) {
cache[n] = fibClosure(n - 1) + fibClosure(n - 2);
}
return cache[n];
};
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment