Process a Big Array in Chunks

Write the code, see it run, pass the checks.

The problem

  • easy
  • Code

Write processInChunks(items, fn, { chunkSize, onProgress }), so a long job doesn't freeze the page. Call fn(item, index) for every item, in order, at most chunkSize of them in one go. After each chunk, call onProgress(done, total) if it was given, where done is how many items have been processed so far and total is the length of items. Then, before the next chunk, give the browser a turn by waiting for a setTimeout with a delay of 0: awaiting a promise isn't enough, because other timers must get to run between chunks. Return a promise of an array of fn's results, in order. An empty array resolves to an empty array.

Your code must pass

  • Resolves with fn's results, in order
  • Calls onProgress after each chunk
  • Lets other timers run between chunks
  • Resolves an empty array to an empty array