Skip to content

Instantly share code, notes, and snippets.

@mcsheffrey
Created October 15, 2013 06:06
Show Gist options
  • Save mcsheffrey/6987201 to your computer and use it in GitHub Desktop.
Save mcsheffrey/6987201 to your computer and use it in GitHub Desktop.
var fibo_useless = function(g, n) {
return n == 0 ? 0 :
n == 1 ? 1 :
g(n-1) + g(n-2);
};
var cachify = function(f, cache) {
return function(n) {
if(!cache[n]) {
var g = cachify(f, cache);
cache[n] = f(g, n);
}
return cache[n];
};
};
var cache = {};
var fibo_caching = cachify(fibo_useless, cache);
alert("fibo_caching(70) = " + fibo_caching(70)); // Very fast on the first call
alert("fibo_caching(70) = " + fibo_caching(70)); // Instantaneous on the second call
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment