import { describe, expect, it } from "vitest"; import { mapWithConcurrency } from "./concurrency.js"; function deferred() { let resolve!: () => void; const promise = new Promise((res) => { resolve = res; }); return { promise, resolve }; } describe("mapWithConcurrency", () => { it("runs all items", async () => { const seen: number[] = []; await mapWithConcurrency([1, 2, 3], 2, async (item) => { seen.push(item); }); expect(seen.sort((a, b) => a - b)).toEqual([1, 2, 3]); }); it("caps active workers at the provided limit", async () => { let active = 0; let maxActive = 0; const releases = Array.from({ length: 5 }, () => deferred()); const promise = mapWithConcurrency([1, 2, 3, 4, 5], 2, async (_item, index) => { active += 1; maxActive = Math.max(maxActive, active); await releases[index]!.promise; active -= 1; }); await Promise.resolve(); releases[0]!.resolve(); releases[1]!.resolve(); await Promise.resolve(); releases[2]!.resolve(); releases[3]!.resolve(); await Promise.resolve(); releases[4]!.resolve(); await promise; expect(maxActive).toBeLessThanOrEqual(2); }); it("clamps invalid concurrency to one worker", async () => { const order: number[] = []; await mapWithConcurrency([1, 2, 3], 0, async (item) => { order.push(item); }); expect(order).toEqual([1, 2, 3]); }); });