Last active
August 29, 2015 14:03
-
-
Save shobith/8dfe0cd08da29fb29a33 to your computer and use it in GitHub Desktop.
memoizing recursive functions in javascript.
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
// 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)); |
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
$ 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