Skip to content

Instantly share code, notes, and snippets.

@dhfromkorea
Created August 3, 2015 18:12
Show Gist options
  • Save dhfromkorea/a794f64095259cce5870 to your computer and use it in GitHub Desktop.
Save dhfromkorea/a794f64095259cce5870 to your computer and use it in GitHub Desktop.
memoized_fibonacci
var fibonacci = function(){
var _cache = [];
var fib = function(i){
if (i < 0) {
console.err('invalid input. i must be >= 0');
return;
}
if (i < 2) {
_cache[i] = i;
return _cache[i];
}
if (!_cache[i]) {
_cache[i] = fib(i-1) + fib(i-2);
}
return _cache[i];
};
return fib;
}
var cachedFibonacci = fibonacci();
// usage
// cachedFibonacci(0) === 0
// cachedFibonacci(1) === 1
// cachedFibonacci(3) === 2
// cachedFibonacci(6) === 8
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment