Created
March 13, 2015 06:16
-
-
Save simongong/48ac5e1faef91454aa92 to your computer and use it in GitHub Desktop.
JavaScript: compute by recursive function call with cache
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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