Memoize in JavaScript
Posted February 15th, 2007 by bard
In JavaScript, functions are objects. No big deal, until you expand that to functions can have state, and realize that things like this become possible:
function fact(n) {
var memo = arguments.callee.memo;
if(!(n in memo))
if(n == 0)
memo[n] = 1;
else
memo[n] = n * fact(n - 1);
return memo[n];
}
fact.memo = {};
(arguments.callee is how you reference a function from within the function itself.)
Wow, that’s eerie… I was explaining memoization to a co-worker today and I used that exact example.
Post new comment