Write processInChunks(items, fn, chunkSize): map a large array without blocking the main thread.
Call fn(item, index) for every item in items, and resolve with the results, in order.
Process at most chunkSize items (default 100) per task, and yield to the event loop between chunks so timers, input, and rendering get a turn.
Reject if fn throws, and reject with a RangeError if chunkSize isn't a positive integer.
async function processInChunks(items, fn, chunkSize = 100) {
// your code
}
// setTimeout(() => console.log("timer"), 0);
// const doubled = await processInChunks([1, 2, 3, 4, 5], (n) => {
// console.log("item", n);
// return n * 2;
// }, 2);
// logs item 1, item 2, timer, item 3, item 4, item 5: the timer got a turn between chunks
// doubled; // [2, 4, 6, 8, 10]
The answer
Write it yourself first. Then compare it with a reference solution and the checks it passes.
Checking your sign-in…