Thursday, May 17th, 2007
One-Line JavaScript Memoization
Oliver Steele has written up some of his implementations of memoization in JavaScript.
He ends up with:
-
-
function memoizeConstantMethod(o, p) {
-
var f = o[p], mf;
-
var s = function(v) {return o[p]=v||mf};
-
((mf = function() {
-
(s(function(){return value})).reset = mf.reset;
-
return value = f.call(this);
-
}).reset = s)();
-
}
-
If you have calculations that you would like to cache, memoization may be a good choice for you.












f, mf, s, v and o with p. Great obfuscation! :D
I know I was just about to say. It annoys the piss out of me when I can’t read the users code. I mean why share it when you do stuff like that.
his blog spells it out though, with loads of examples… great work!
the shorter memoizeConstantMethod version is broken and does not work if called several times. because it references to the ‘value’ variable from global scope.
Could be easily corrected by adding ‘var value’
function memoizeConstantMethod(o, p) {
var f = o[p], mf, value;
var s = function(v) {return o[p]=v||mf};
((mf = function() {
(s(function(){return value})).reset = mf.reset;
return value = f.call(this);
}).reset = s)();
}
sory for this test