Skip to content

Instantly share code, notes, and snippets.

@EvidentlyCube
Created April 26, 2019 08:30
Show Gist options
  • Save EvidentlyCube/e8823a81070ebb273c0d37fe725759b6 to your computer and use it in GitHub Desktop.
Save EvidentlyCube/e8823a81070ebb273c0d37fe725759b6 to your computer and use it in GitHub Desktop.
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