Skip to content

Instantly share code, notes, and snippets.

@shobith
Last active August 29, 2015 14:03
Show Gist options
  • Save shobith/8dfe0cd08da29fb29a33 to your computer and use it in GitHub Desktop.
Save shobith/8dfe0cd08da29fb29a33 to your computer and use it in GitHub Desktop.
memoizing recursive functions in javascript.
// attempt to make a swift-style generic memoize idiom ( https://gist.github.com/berkus/8a9e104f8aac5d025eb5 )
function memoize(body) {
var memo = {};
return function memo_op(param) {
if (memo[param] === undefined)
memo[param] = body(memo_op, param);
return memo[param];
}
}
var fibonacci = memoize(function (fibonacci, n) {
return (n < 2 ? n : fibonacci(n-1) + fibonacci(n-2));
});
console.log(fibonacci(45) / fibonacci(44));
$ time node memoize.js
1.618033988749895
real 0m0.068s
user 0m0.044s
sys 0m0.021s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment