A simple Pool class I used for Trans Neuronica
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
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