Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A simple Pool class I used for Trans Neuronica
export class Pool<T>
{
private readonly _pool: T[];
private readonly _construct: () => T;
private readonly _autoHydrateSize: number;
private _indexInPool: number;
constructor(initialCapacity: number, construct: () => T, autoHydrateSize: number = 1)
{
this._pool = [];
this._indexInPool = 0;
this._autoHydrateSize = autoHydrateSize;
this._construct = construct;
this.hydrate(initialCapacity);
}
public getOne()
{
if (this._indexInPool === 0) {
this.hydrate(this._autoHydrateSize);
}
return this._pool[--this._indexInPool];
}
public hydrate(instancesToAdd: number)
{
if (instancesToAdd < 0) {
throw new Error("`instancesToAdd` cannot be less than 0");
}
while (instancesToAdd-- > 0) {
this._pool[this._indexInPool++] = this._construct();
}
}
public release(instance: T)
{
this._pool[this._indexInPool++] = instance;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.