Skip to content

Instantly share code, notes, and snippets.

@gordonbrander
Forked from anonymous/memoize.js
Created April 29, 2014 16:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gordonbrander/11405769 to your computer and use it in GitHub Desktop.
Save gordonbrander/11405769 to your computer and use it in GitHub Desktop.
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