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
fnagain. - When the promise settles, resolved or rejected, the key is released, so the next call with that key calls
fnagain. - Calls with different keys never affect each other.
- The call that actually runs
fnpasses its own arguments andthisto 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
Give it a real attempt first. Run shows which examples fail.
Saved automatically
Run checks the 3 visible tests, Submit all 8. ⌘Enter runs, ⌘⇧Enter submits.