103Implement a mapLimit() with AbortSignal, ordered results, and configurable error-handling policies
Problem
Implement mapLimit(items, limit, mapper, { signal, errorPolicy = "fail-fast" } = {}). It calls mapper(item, index, { signal }) with at most limit calls in flight and keeps results in input order. The signal given to each mapper call is aborted whenever the whole operation is stopped, so mappers can cancel their own work.
Error policies:
"fail-fast": on the first failure, abort the in-flight calls, start nothing new, and reject with that error."settle": never reject; resolve with{ status: "fulfilled", value }or{ status: "rejected", reason }per item."aggregate": run everything; if any call failed, reject with anAggregateErrorwhoseerrorsare in input order; otherwise resolve with the values.
Cancellation: when the caller's signal aborts, abort in-flight calls, start nothing new, and reject with signal.reason (also if it was aborted before the call).
Other rules: limit must be at least 1 (else reject with a RangeError); Infinity is allowed. It must handle 100,000 items without creating 100,000 pending promises at once.
Try it yourself
Write your solution, run it, then submit to check it against the tests.
Press Run or ⌘ Enter to execute your code.
Step-by-step
Create an AbortController for the whole operation. Every mapper receives its signal. Aborting it (on a fail-fast error or a caller abort) reaches every in-flight call at once.
Unlock the full solution
What's inside
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Tests
Includes 2 code listings, 5 edge cases, 4 follow-up questions.
One-time payment by UPI, card or net banking. Launch price.