Skip to content

Instantly share code, notes, and snippets.

@kigiri
Created March 28, 2026 19:39
Show Gist options
  • Select an option

  • Save kigiri/63f217cbbd543783820d21ca1759e2f4 to your computer and use it in GitHub Desktop.

Select an option

Save kigiri/63f217cbbd543783820d21ca1759e2f4 to your computer and use it in GitHub Desktop.
TS / JS `using` queue
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