Javascript Memoize
function memoize(f) { eval(f + ' = ' + f + '.memoize()') }
Function.prototype.memoize = function () {
var old = this;
var cache = new Array();
return(
function(x) {
if (cache[x]) return(cache[x]);
else return(cache[x] = old(x));
}
);
}
memoize('some_really_difficult_calculation'); // hmm this looks surprisingly
memoize('Math.pow'); // like this other "web" language in
memoize('Math.sqrt'); // popular usage in today's society (Fortran '77)
memoize('Math.random'); // JUST JOSHIN' HERE PEOPLE!!!
I'm not the only person to port memoize to ECMAScript either.
August 15, 2007 update: Another implementation. I think both of these versions are better than mine, since they can deal with functions with more than one argument (but then I really try to avoid writing multiple arg functions). Mine also uses eval(), though that was mostly just to get an interface similar to Perl's Memoize, which isn't necessary.
May 11, 2005 : link