Exercise 9: Batch Process Array with Concurrency Limit

Problem Statement

Function `batchProcess(items, processor, concurrency)` banao jo items ko process kare with concurrency limit. Example: batchProcess([1,2,3,4], async (x) => x*2, 2) → max 2 parallel

Sample Output:

await batchProcess([1,2,3,4], async (x) => x*2, 2) => [2, 4, 6, 8]
// Processes max 2 items at a time

Solution

const batchProcess = async (items, processor, concurrency) => {
  const results = [];
  for (let i = 0; i < items.length; i += concurrency) {
    const batch = items.slice(i, i + concurrency);
    const batchResults = await Promise.all(batch.map(processor));
    results.push(...batchResults);
  }
  return results;
};

Explanation

Overall Goal:

  • Items ko batches me process karna with concurrency limit.

Real world:

  • API calls: rate limiting.
  • Processing: controlled parallelism.