Reduce an array with an async reducer
Applying a queue of offline edits to a document, or importing rows one at a time so each can see the effect of the previous one, both need a fold where every step waits for the last.
Implement reduceAsync(items, reducer, initial). Starting from initial, call reducer(accumulator, item, index) for each item in order, awaiting the result before moving on, and resolve with the final accumulator. The reducer may return a plain value or a promise. An empty array resolves with initial without calling the reducer. If the reducer throws or rejects, reject with that reason and stop — later items are not processed.
Arguments
itemsArray<T>- The input array to fold.
reducer(acc: U, item: T, index: number) => U | Promise<U>- Called for each item with the accumulator, item, and index.
initialU- The starting value for the accumulator.
Returns
Promise<U> — A promise that resolves with the final accumulator. Rejects on the first failure and stops.
Examples
const total = await reduceAsync(
[1, 2, 3, 4],
async (sum, n) => sum + n,
0
);
// total === 10Each step awaits the previous accumulator before continuing.
let calls = 0;
const value = await reduceAsync([], async (acc) => { calls++; return acc; }, "untouched");
// value === "untouched", calls === 0 — reducer never ranEmpty input returns initial without invoking the reducer.
What it has to do
- Process items strictly in order, awaiting each result.
- Pass
(accumulator, item, index)to the reducer. - Resolve with
initialfor an empty array, without calling the reducer. - Support reducers that return plain values.
- Reject on the first failure and stop processing.
Notes
- Each step must await the previous accumulator —
Promise.all+reducewon't work because later steps depend on earlier ones. - A rejection halts the fold immediately; subsequent items are not visited.
Stuck? The javascript course covers everything this challenge needs.
- 1.folds the array into one value
- 2.processes items in order even with uneven delays
- 3.passes the index to the reducer
- 4.returns the initial value for an empty array
- 5.stops on the first rejection
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.