diff --git a/src/process-in-chunks.test.ts b/src/process-in-chunks.test.ts index bd9f8a8..93df451 100644 --- a/src/process-in-chunks.test.ts +++ b/src/process-in-chunks.test.ts @@ -208,6 +208,22 @@ describe("processInChunks", () => { describe("processInChunksByChunk", () => { describe("core behavior", () => { + it("passes correct chunk index to callback", async () => { + const items = [1, 2, 3, 4, 5, 6]; + const receivedIndices: number[] = []; + + await processInChunksByChunk( + items, + async (chunk, index) => { + receivedIndices.push(index); + return chunk.length; + }, + { chunkSize: 2 }, + ); + + expect(receivedIndices).toEqual([0, 1, 2]); + }); + it("passes entire chunk array to callback", async () => { const items = [1, 2, 3, 4, 5, 6]; const receivedChunks: number[][] = []; diff --git a/src/process-in-chunks.ts b/src/process-in-chunks.ts index 850db28..6e90b8d 100644 --- a/src/process-in-chunks.ts +++ b/src/process-in-chunks.ts @@ -138,13 +138,11 @@ export async function processInChunksByChunk( const errorMessagesSet = new Set(); const results: (R | undefined)[] = []; - let overallIndex = 0; - for (const [index, items] of chunks.entries()) { logIfVerbose(`Processing chunk ${index + 1}/${chunks.length}`); try { - const processPromise = processFn(items, overallIndex); + const processPromise = processFn(items, index); /** Run throttle wait in parallel with processing if throttling is enabled */ const result = await (throttleSeconds > 0 @@ -154,14 +152,12 @@ export async function processInChunksByChunk( : processPromise); results.push(result); - overallIndex += items.length; } catch (err) { if (!noThrow) { throw err; // Rethrow original error immediately } errorMessagesSet.add(getErrorMessage(err)); results.push(undefined); - overallIndex += items.length; } }