Created
September 26, 2013 19:05
-
-
Save mcsheffrey/6719018 to your computer and use it in GitHub Desktop.
A Memoization Pattern - JavaScript Patterns
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
var myFunc = function (param) { | |
if (!myFunc.cache[param]) { | |
var result = {}; | |
// ... expensive operation ... | |
myFunc.cache[param] = result; | |
} | |
return myFunc.cache[param]; | |
}; | |
// cache storage | |
myFunc.cache = {}; | |
//slightly different example | |
var memoize = function(fn) { | |
var cache = {}; | |
return function(arg) { | |
if (arg in cache) return cache[arg]; | |
cache[arg] = fn(arg); | |
return cache[arg]; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment