Created
April 29, 2014 16:45
-
-
Save anonymous/11405764 to your computer and use it in GitHub Desktop.
memoize() -- simple, flexible JS memoization
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
function id(x) { | |
return x; | |
} | |
// Memoize a function -- creates a new function that will cache the results of | |
// the first return by serializing inputs as a key. | |
// | |
// * `fn`: the function to be memoized. | |
// * `hash`: a function to create the cache key. | |
// * `out`: a function to process memoized data on the way out. Useful if you need | |
// to return an object copy instead of a reference to first return value. | |
function memoize(fn, hash, out) { | |
var memos = {}; | |
hash = hash || id; | |
out = out || id; | |
return function() { | |
var key = hash.apply(null, arguments); | |
var x = memos[key] != null ? | |
memos[key] : memos[key] = fn.apply(null, arguments); | |
return out(x); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment