Created
August 22, 2024 12:24
-
-
Save al-arz/d22a15415bee254304e2b6626894ec04 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
import { DisplayObject } from "@pixi/display"; | |
export class Pool<T extends DisplayObject> { | |
private inactive: T[] = []; | |
public active: T[] = []; | |
private readonly createObject: () => T; | |
private readonly resetObject: (elem: T) => void; | |
private readonly destroyObject: (elem: T) => void; | |
constructor( | |
createObject: () => T, | |
resetObject: (elem: T) => void, | |
destroyObject: (elem: T) => void | |
) { | |
this.createObject = createObject; | |
this.resetObject = resetObject; | |
this.destroyObject = destroyObject; | |
} | |
public getInstance(): T { | |
const instance = this.inactive.pop() || this.createObject(); | |
this.active.push(instance); | |
this.resetObject(instance); | |
return instance; | |
} | |
public release(instance: T): void { | |
instance.parent && instance.parent.removeChild(instance); | |
this.active = this.active.filter((i) => i != instance); // remove passed instance | |
this.inactive.push(instance); | |
} | |
public destroy(): void { | |
[...this.active, ...this.inactive].forEach((instance) => | |
this.destroyObject(instance) | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment