Skip to content

Instantly share code, notes, and snippets.

@aarti
Created August 6, 2015 20:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aarti/15f3d01e78c922547c87 to your computer and use it in GitHub Desktop.
Save aarti/15f3d01e78c922547c87 to your computer and use it in GitHub Desktop.
var Fib = {
compute: function(n) {
return n < 2 ? 1 : Fib.compute(n-1)+Fib.compute(n-2)
}
}
function memoize(obj,prop) {
var cache = {}
var fn = obj[prop]
return function(x) {
if (x in cache) {
console.log('retrieved value from cache for', x)
}
return x in cache ? cache[x] :cache[x] = fn(x)
}
}
Fib.compute = memoize(Fib, "compute")
console.log(Fib.compute(1))
console.log(Fib.compute(4))
console.log(Fib.compute(5))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment