Skip to content

Instantly share code, notes, and snippets.

@al-arz
Created August 22, 2024 12:24
Show Gist options
  • Save al-arz/d22a15415bee254304e2b6626894ec04 to your computer and use it in GitHub Desktop.
Save al-arz/d22a15415bee254304e2b6626894ec04 to your computer and use it in GitHub Desktop.
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