Skip to content
Onsite

Dedupe Concurrent Async Calls

MediumP3Coding

Implement dedupe(fn, keyFn) for an async function fn. It returns a wrapper that shares one in-flight call between callers with the same key.

  • keyFn(...args) computes the key for a call; it defaults to (...args) => JSON.stringify(args).
  • If a call with the same key is already in flight (its promise is still pending), the wrapper returns that same promise and does not call fn again.
  • When the promise settles, resolved or rejected, the key is released, so the next call with that key calls fn again.
  • Calls with different keys never affect each other.
  • The call that actually runs fn passes its own arguments and this to it.

Example 1

Input
const load = dedupe(fetchUser); const a = load(1); const b = load(1);
Output
fetchUser runs once; a === b

Constraints

  • fn returns a promise.
  • At most 10^4 keys in flight at once.

Hints

Run checks the 3 visible tests, Submit all 8.