Skip to content

Instantly share code, notes, and snippets.

@celwell
Created January 14, 2019 20:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save celwell/c609f6160263f2fc0b505e2c038c183d to your computer and use it in GitHub Desktop.
Save celwell/c609f6160263f2fc0b505e2c038c183d to your computer and use it in GitHub Desktop.
JS function "memoize": Takes a function, f, and returns a memoized version of f.
// Takes a function, f, and returns a memoized version of f.
// Note: only memoize pure, idempotent functions
var memoize = function (f) {
let store = new Map();
return function (...args) {
const k = JSON.stringify(args);
return (store.has(k) ?
store.get(k) :
store.set(k, f(...args)).get(k));
};
};
/*
Example usage:
var do_sum = function (x, y) {
console.log('did calculation');
return x + y;
};
var memoized_do_sum = memoize(do_sum);
memoized_do_sum(3, 12);
// output: "did calculation", 15
memoized_do_sum(3, 12);
// output: 15
memoized_do_sum(3, 12);
// output: 15
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment