Created
September 24, 2022 22:09
-
-
Save howmanysmall/41500ac3df51c0e454a8a3f922e731fb to your computer and use it in GitHub Desktop.
This file contains hidden or 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 default class ObjectPool<T extends object> { | |
| public ExpansionSize = 5; | |
| public Generator: () => T; | |
| public Cleaner: (object: T) => void; | |
| public Reserve: Array<T>; | |
| public InUse: Array<T>; | |
| public constructor(precreateAmount: number, generator: () => T, cleaner: (object: T) => void) { | |
| this.Generator = generator; | |
| this.Cleaner = cleaner; | |
| this.ReserveCache = new Array<T>(precreateAmount); | |
| this.InUse = new Array<T>(precreateAmount); | |
| for (const index of $range(0, precreateAmount)) | |
| this.ReserveCache[index] = generator(); | |
| } | |
| public GetObject(): T { | |
| const reserveCache = this.ReserveCache; | |
| if (reserveCache.size() === 0) | |
| for (const _ of $range(0, this.ExpansionSize)) | |
| reserveCache.push(this.Generator()); | |
| const object = reserveCache.pop()!; | |
| this.InUse.push(object); | |
| return object; | |
| } | |
| public ReturnObject(object: T) { | |
| const index = this.InUse.indexOf(object); | |
| if (index !== undefined) { | |
| this.Cleaner(object); | |
| this.InUse.unorderedRemove(index); | |
| this.ReserveCache.push(object); | |
| } | |
| } | |
| public Destroy() { | |
| for (const object of this.InUse) this.Cleaner(object); | |
| for (const object of this.ReserveCache) this.Cleaner(object); | |
| table.clear(this); | |
| setmetatable(this, undefined!); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment