Wednesday, January 25, 2012

Javascript Memoization Pattern


It happens sometime that you need to cache some data which has produced by a complex operation. Caching data helps you not to do repeat the complex operation. Caching the results of an operation is also known as Memoization. Followings are too example of this pattern.

var setCache = function (param,val) {


       setCache.cache[param] =val;
       return setCache.cache[param];
 };
setCache.cache={};

or you can just save the result of a function inside the  function:


var setCache = function (param) {
       if (!setCache.cache[param]){
          var res;


          //do the complex and heavy operation 
          //here and assign the  result to 'res'


          setCache.cache[param] =res;
       }
       return setCache.cache[param];
};
setCache.cache={};




Also its possible to serialize the complex structure to string with JSON.

No comments:

Post a Comment