Daniel Rench

Web application development : Servers : Networks : E-Mail : DNS : Databases : Programming for hire

previous : contact : linkedin : code : links : pictures : facebook : twitter : next

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.

<< R / P / S and MS-Tick XP | Home | Portfolio | Contact | Husker Du? >>