Thursday, May 17th, 2007

One-Line JavaScript Memoization

Category: Examples, JavaScript, Library

<>p>Oliver Steele has written up some of his implementations of memoization in JavaScript.

He ends up with:

javascript
< view plain text >
  1. function memoizeConstantMethod(o, p) {
  2.   var f = o[p], mf;
  3.   var s = function(v) {return o[p]=v||mf};
  4.   ((mf = function() {
  5.     (s(function(){return value})).reset = mf.reset;
  6.     return value = f.call(this);
  7.   }).reset = s)();
  8. }

If you have calculations that you would like to cache, memoization may be a good choice for you.

Related Content:

Posted by Dion Almaer at 7:24 am
5 Comments

++++-
4.1 rating from 34 votes

5 Comments »

Comments feed TrackBack URI

f, mf, s, v and o with p. Great obfuscation! :D

Comment by tony — May 17, 2007

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.

Comment by iknowright — May 17, 2007

his blog spells it out though, with loads of examples… great work!

Comment by iknowright — May 17, 2007

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)();
}

Comment by atany — May 17, 2007

sory for this test

Comment by test — May 18, 2007

Leave a comment

You must be logged in to post a comment.