Created
August 21, 2012 10:57
-
-
Save tuzz/3414496 to your computer and use it in GitHub Desktop.
JavaScript memoized recursion
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
var MyApp = {}; | |
MyApp.memoizer = function (memo, formula) { | |
var recur, result; | |
recur = function (n) { | |
result = memo[n]; | |
if (typeof result !== 'number') { | |
result = formula(recur, n); | |
memo[n] = result; | |
} | |
return result; | |
}; | |
return recur; | |
}; | |
MyApp.fib = MyApp.memoizer([0, 1], function (recur, n) { | |
return recur(n - 1) + recur(n - 2); | |
}); | |
MyApp.fact = MyApp.memoizer([1, 1], function (recur, n) { | |
return n * recur(n - 1); | |
}); | |
var i; | |
for (i = 0; i <= 20; i += 1) { | |
document.write(i + ": " + MyApp.fib(i) + ", " + MyApp.fact(i) + "<br />"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment