Created
January 17, 2024 17:14
-
-
Save jtmthf/6f972f00e56f4667ac47485724c29e84 to your computer and use it in GitHub Desktop.
This file contains 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
interface ResourcePoolOptions<T> { | |
defaultSize: number; | |
maxSize: number; | |
create: () => T; | |
} | |
interface Resource<T> extends Disposable { | |
value: T; | |
} | |
class ResourcePool<T> { | |
#free: Set<T>; | |
#claimed: Set<T>; | |
#defaultSize: number; | |
#maxSize: number; | |
#create: () => T; | |
constructor({defaultSize, maxSize, create}: ResourcePoolOptions<T>) { | |
this.#free = new Set(Array.from({length: defaultSize}, () => create())); | |
this.#claimed = new Set(); | |
this.#defaultSize = defaultSize; | |
this.#maxSize = maxSize; | |
this.#create = create; | |
} | |
get size(): number { | |
return this.#free.size + this.#claimed.size; | |
} | |
get(): Resource<T> { | |
if (this.#free.size > 0) { | |
const [value] = this.#free.values(); | |
this.#free.delete(value); | |
this.#claimed.add(value); | |
return { | |
value, | |
[Symbol.dispose]: () => { | |
this.#claimed.delete(value); | |
this.#free.add(value); | |
} | |
} | |
} else if (this.size < this.#maxSize) { | |
this.#free.add(this.#create()); | |
return this.get(); | |
} else { | |
throw new Error('max size exceeded'); | |
} | |
} | |
} | |
const pool = new ResourcePool<ArrayBuffer>({ | |
defaultSize: 20, | |
maxSize: 50, | |
create: () => new ArrayBuffer(100), | |
}); | |
using resource = pool.get(); | |
const buffer = resource.value; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment