The Ashes
Technology, Science and other news
May 10, 2009
A Better Javascript Memoizer
Filed under : General
We have covered memoizers in the past, but John Hann has posted on a nice implementation that takes advantage of closures, arity, and recursion — 3 concepts/features that Javascript was meant to use.
It leads to this generic version:
JAVASCRIPT:
-
-
// memoize: a general-purpose function to enable a function to use memoization
-
// func: the function to be memoized
-
// context: the context for the memoized function to execute within
-
// Note: the function must use explicit, string-serializable parameters
-
function memoize (func, context) {
-
function memoizeArg (argPos) {
-
var cache = {};
-
return function () {
-
if (argPos == 0) {
-
if (!(arguments[argPos] in cache)) {
-
cache[arguments[argPos]] = func.apply(context, arguments);
-
}
-
return cache[arguments[argPos]];
-
}
-
else {
-
if (!(arguments[argPos] in cache)) {
-
cache[arguments[argPos]] = memoizeArg(argPos – 1);
-
}
-
return cache[arguments[argPos]].apply(this, arguments);
-
}
-
}
-
}
-
// JScript doesn’t grok the arity property, but uses length instead
-
var arity = func.arity || func.length;
-
return memoizeArg(arity – 1);
-
}
-
and this conclusion:
Yes, memoization is a neat concept. But why use it rather than just hand-coded caching mechanisms? It’s easy enough to write a caching routine, right? Here are a few good reasons:
- hand-coded caching mechanisms obfuscate your code
- multi-variate caching routines are bulky in Javascript
- fewer lines of code means fewer bugs
- Java programmers will think more highly of you 😉
Tags :
No Comments