Created
March 28, 2026 19:39
-
-
Save kigiri/63f217cbbd543783820d21ca1759e2f4 to your computer and use it in GitHub Desktop.
TS / JS `using` queue
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const makeQueue = (max: number) => { | |
| let slotsUsed = 0 | |
| const pendingSlots: Array<(slot: Slot) => void> = [] | |
| type Slot = { [Symbol.dispose](): void } | |
| const freeSlot = { | |
| [Symbol.dispose]() { | |
| const next = pendingSlots.shift() | |
| next ? next(freeSlot) : slotsUsed-- | |
| }, | |
| } | |
| const queueSlot = (resolve: (slot: Slot) => void) => pendingSlots.push(resolve) | |
| return (): Slot | Promise<Slot> => { | |
| if (slotsUsed >= max) return new Promise<Slot>(queueSlot) | |
| slotsUsed++ | |
| return freeSlot | |
| } | |
| } | |
| // usage: | |
| // const getSlot = makeQueue(30) // limit to 30 parallel slots | |
| // using _ = await getSlot() // will use one slot and dispose directly |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment