ruk·si

🍦 JavaScript
Memoization

Updated at 2013-04-28 12:25

This note contains JavaScript memoization snippets. Memoization is caching function returns for particular parameters. Helps to avoid expensive computation if the result is not going to change. Also called function cache.

Function with one parameter.

var myFunc = function(parameter) {
  if ( ! myFunc.cache.hasOwnProperty(parameter) ) {
    var result = {};
    // ... expensive operation ...
    myFunc.cache[parameter] = result;
  }
  return myFunc.cache[parameter];
};

// Cache storage definition.
myFunc.cache = {};

Function with multiple parameters using JSON stringify.

var myFunc = function(param1, param2) {
  var cacheKey = JSON.stringify( Array.prototype.slice.call(arguments) );
  if ( ! myFunc.cache[cacheKey] ) {
    var result = {};
    // ... expensive operation ...
    myFunc.cache[cacheKey] = result;
  }
  return myFunc.cache[cacheKey];
};

// Cache storage definition.
myFunc.cache = {};

Function with multiple parameters using arguments.callee.

var myFunc = function(param1, param2) {
  var f = arguments.callee;
  if ( ! f.cache[parameter] ) {
    var result = {};
    // ... expensive operation ...
    f.cache[parameter] = result;
  }
  return f.cache[parameter];
};

// Cache storage definition.
myFunc.cache = {};