Skip to content

Instantly share code, notes, and snippets.

@aarti
Created August 6, 2015 20:26
Show Gist options
  • Save aarti/9b40e2ef4b2984821442 to your computer and use it in GitHub Desktop.
Save aarti/9b40e2ef4b2984821442 to your computer and use it in GitHub Desktop.
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