Skip to content

Instantly share code, notes, and snippets.

@dannycallaghan
Created October 9, 2013 08:08
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dannycallaghan/6897874 to your computer and use it in GitHub Desktop.
Save dannycallaghan/6897874 to your computer and use it in GitHub Desktop.
Memoization Pattern From 'JavaScript Patterns' (O'Reilly) by Stoyan Stefanov.
/* Memoization Pattern */
// a single parameter example
var myFunc = function ( param ) {
if ( !myFunc.cache[ param ] ) {
var result = {};
// ... expensive operation ...
myFunc.cache[ param ] = result;
}
return myFunc.cache[ param ];
};
// cache storage
myFunc.cache = {};
// a multiple params solution
var myFunc = function () {
// serialize the params as a JSON string
var cachekey = JSON.stringify( Array.prototype.slice.call( arguments ) ),
result;
if ( !myFunc.cache[ param ] ) {
result = {};
// ... expensive operation ...
myFunc.cache[ cachekey ] = result;
}
return myFunc.cache[ cachekey ];
};
// cache storage
myFunc.cache = {};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment