Skip to content

Instantly share code, notes, and snippets.

Created April 29, 2014 16:45
Show Gist options
  • Save anonymous/11405764 to your computer and use it in GitHub Desktop.
Save anonymous/11405764 to your computer and use it in GitHub Desktop.
memoize() -- simple, flexible JS memoization
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