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