Skip to content

Instantly share code, notes, and snippets.

@raybellis
Created July 31, 2020 14:56
Show Gist options
  • Save raybellis/5f1206644c8f70acd2f3a11b0f9a65eb to your computer and use it in GitHub Desktop.
Save raybellis/5f1206644c8f70acd2f3a11b0f9a65eb to your computer and use it in GitHub Desktop.
Generic memoize function supporting multiple parameter key lookups
function memoize(factory, ctx, mapper) {
const cache = new Map();
return function(...keys) {
const key = mapper ? mapper(keys) : keys[0];
if (!cache.has(key)) {
cache.set(key, factory.apply(ctx, keys));
}
console.debug(cache);
return cache.get(key);
}
}
@raybellis
Copy link
Author

example usage:

const multiply = memoize((a, b) => a * b, undefined, JSON.stringify);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment