Created
August 6, 2015 20:26
-
-
Save aarti/9b40e2ef4b2984821442 to your computer and use it in GitHub Desktop.
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
function fibonacci(n) { | |
return n < 2 ? 1 : fibonacci(n-1)+fibonacci(n-2) | |
} | |
function memoize(fn) { | |
var cache = {} | |
return function(x) { | |
if (x in cache) { | |
console.log('retrieved value from cache for', x) | |
} | |
return x in cache ? cache[x] :cache[x] = fn.apply(this,arguments) | |
} | |
} | |
fibonacci = memoize(fibonacci) | |
console.log(fibonacci(1)) | |
console.log(fibonacci(4)) | |
console.log(fibonacci(5)) | |
// → node memoize_fibonacci.js | |
// 1 | |
// retrieved value from cache for 1 | |
// retrieved value from cache for 1 | |
// retrieved value from cache for 2 | |
// 5 | |
// retrieved value from cache for 4 | |
// retrieved value from cache for 3 | |
// 8 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment