Skip to content

Instantly share code, notes, and snippets.

@dannycallaghan
Created October 9, 2013 08:08
Show Gist options
  • Select an option

  • Save dannycallaghan/6897874 to your computer and use it in GitHub Desktop.

Select an option

Save dannycallaghan/6897874 to your computer and use it in GitHub Desktop.

Revisions

  1. dannycallaghan created this gist Oct 9, 2013.
    28 changes: 28 additions & 0 deletions Memoization Pattern.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,28 @@
    /* 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 = {};