Created
October 9, 2013 08:08
-
-
Save dannycallaghan/6897874 to your computer and use it in GitHub Desktop.
Memoization Pattern From 'JavaScript Patterns' (O'Reilly) by Stoyan Stefanov.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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