Skip to content

Instantly share code, notes, and snippets.

@icodejs
Created June 6, 2012 16:58
Show Gist options
  • Save icodejs/2883282 to your computer and use it in GitHub Desktop.
Save icodejs/2883282 to your computer and use it in GitHub Desktop.
JS: Memorisation Pattern
// You can add custom properties to your functions at any time. One use case for custom
// properties is to cache the results (the return value) of a function, so the next time the
// function is called, it doesn’t have to redo potentially heavy computations. Caching the
// results of a function is also known as memoization.
var myFunc = function (param) {
if (!myFunc.cache[param]) {
var result = {};
// ... expensive operation ...
myFunc.cache[param] = result;
}
return myFunc.cache[param];
};
// cache storage
myFunc.cache = {};
// The function myFunc creates a property cache, accessible as
// usual via myFunc.cache. The cache property is an object (a hash) where the parameter
// param passed to the function is used as a key and the result of the computation is the
// value.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment