Skip to main content

Posts

Showing posts from January, 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...

Chaining Pattern

With Chaining Pattern you can call object methods one after the others without assigning the result to other variables or break them in multiple statement or lines. For example: myobj.func1().func2(1,2,3).func3('fsnjk'); This pattern is only useful when object functions do not have to special return so, this pattern can  implemented by returning this in each object function. For example: var myelm={         hide: function(second){                 //code for hiding                  return this;         },         fadeIn: function(second){                 //code for fading                  return this;         } }; myelm.hide(1).fadeIn(2);