| 677 | * @returns Array of results |
| 678 | */ |
| 679 | export async function processInBatches<T, R>( |
| 680 | items: T[], |
| 681 | batchSize: number, |
| 682 | processor: (item: T, index: number) => Promise<R>, |
| 683 | onBatchComplete?: (completed: number, total: number) => void |
| 684 | ): Promise<R[]> { |
| 685 | const results: R[] = []; |
| 686 | |
| 687 | for (let i = 0; i < items.length; i += batchSize) { |
| 688 | const batch = items.slice(i, Math.min(i + batchSize, items.length)); |
| 689 | const batchResults = await Promise.all( |
| 690 | batch.map((item, idx) => processor(item, i + idx)) |
| 691 | ); |
| 692 | results.push(...batchResults); |
| 693 | |
| 694 | if (onBatchComplete) { |
| 695 | onBatchComplete(Math.min(i + batchSize, items.length), items.length); |
| 696 | } |
| 697 | |
| 698 | // Allow GC between batches |
| 699 | if (global.gc) { |
| 700 | global.gc(); |
| 701 | } |
| 702 | } |
| 703 | |
| 704 | return results; |
| 705 | } |
| 706 | |
| 707 | /** |
| 708 | * Simple mutex lock for preventing concurrent operations |