Created
June 6, 2012 16:58
-
-
Save icodejs/2883282 to your computer and use it in GitHub Desktop.
JS: Memorisation Pattern
This file contains hidden or 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
// 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