Last active
August 29, 2015 14:23
-
-
Save tajpure/56545b72ab0b2bc90706 to your computer and use it in GitHub Desktop.
Memoizer
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
// The demo comes from <<JavaScript:The Good Parts>>. | |
var memoizer = function (memo, formula) { | |
var recur = function (n) { | |
var result = memo[n]; | |
if (typeof result !== 'number') { | |
result = formula(recur, n); | |
memo[n] = result; | |
} | |
return result; | |
}; | |
return recur; | |
}; | |
var fibonacci = memoizer([0, 1], function (recur, n) { | |
return recur(n - 1) + recur(n - 2); | |
}); | |
var factorial = memoizer([1, 1], function (recur, n) { | |
return n * recur(n - 1); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment