Batch Async Calls
HardP3Coding
Implement createBatcher(batchFn), a DataLoader-style helper that turns many single lookups into one batched call.
batchFn(keys) is an async function that takes an array of keys and returns a promise of an array of results in the same order and with the same length. createBatcher returns a function load(key) that returns a promise for that key's result.
- All
loadcalls made in the same synchronous run (before the current call stack unwinds and microtasks run) are collected and answered by one call tobatchFn. - The same key requested several times in one batch is sent once; every caller gets the same result.
- Calls made after that batch was dispatched start a new batch.
- If
batchFnrejects, every promise of that batch rejects with the same error. If it returns something that is not an array of the same length as the keys, every promise of that batch rejects with anErrorwhose message contains"same length".
Example 1
- Input
- const load = createBatcher(async (ids) => ids.map(id => id * 10)); const [a, b] = await Promise.all([load(1), load(2)]);
- Output
- a = 10, b = 20, and batchFn ran once with [1, 2]
Constraints
- Keys are primitives (compared like Map keys).
- At most 10^4 calls per batch.
Hints
Give it a real attempt first. Run shows which examples fail.
Saved automatically
Run checks the 3 visible tests, Submit all 10. ⌘Enter runs, ⌘⇧Enter submits.