Skip to content

Instantly share code, notes, and snippets.

@simongong
Created March 13, 2015 06:16
Show Gist options
  • Save simongong/48ac5e1faef91454aa92 to your computer and use it in GitHub Desktop.
Save simongong/48ac5e1faef91454aa92 to your computer and use it in GitHub Desktop.
JavaScript: compute by recursive function call with cache
/*
* Extract from <JavaScript: The Good Parts>
* General routine with cache for recursive function invoking
*/
var cacheCompute = function(cache, compute){
var shell = function(n){
var result = cache[n];
if(typeof result !== 'number'){
result = compute(shell, n);
cache[n] = result;
}
return result;
};
return shell;
}
var fibonacciInstance = cacheCompute([0, 1], function(shell, n){
return shell(n-1) + shell(n-2);
});
/*
* Compute fibonacci with cache
*/
var fibonacci = function(){
var cache = [0, 1];
var fib = function(n) {
var result = cache[n];
if(typeof result !== 'number'){
result = fib(n-1) + fib(n-2);
cache[n] = result;
}
return result;
};
return fib;
}();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment