Created
August 3, 2015 18:12
-
-
Save dhfromkorea/a794f64095259cce5870 to your computer and use it in GitHub Desktop.
memoized_fibonacci
This file contains 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
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