Skip to content

Instantly share code, notes, and snippets.

@atishay
Created April 6, 2019 16:30
Show Gist options
  • Select an option

  • Save atishay/12150b34c2294f12221da97d221932ab to your computer and use it in GitHub Desktop.

Select an option

Save atishay/12150b34c2294f12221da97d221932ab to your computer and use it in GitHub Desktop.
function memoize(func, resolver) {
const memoized = function(...args) {
const key = resolver ? resolver.apply(this, args) : args[0]
const cache = memoized.cache
if (cache.has(key)) {
return cache.get(key)
}
const result = func.apply(this, args)
memoized.cache = cache.set(key, result) || cache
return result
}
memoized.cache = new Map();
return memoized
}
// Usage
let get = memoize(async (...args) => {
...
return data;
});
const A = async () => await get('x');
const B = async () => await get('x');
const C = async () => await get('y');
const D = async () => await get('x');
// A and B in parallel
await Promise.all([A(), B(), C()]);
// Get is finished already.
await D();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment