pixi.js
Version:
<p align="center"> <a href="https://pixijs.com" target="_blank" rel="noopener noreferrer"> <img height="150" src="https://files.pixijs.download/branding/pixijs-logo-transparent-dark.svg?v=1" alt="PixiJS logo"> </a> </p> <br/> <p align="center">
83 lines (80 loc) • 2.03 kB
JavaScript
'use strict';
"use strict";
class Pool {
/**
* Constructs a new Pool.
* @param ClassType - The constructor of the items in the pool.
* @param {number} [initialSize] - The initial size of the pool.
*/
constructor(ClassType, initialSize) {
this._pool = [];
this._count = 0;
this._index = 0;
this._classType = ClassType;
if (initialSize) {
this.prepopulate(initialSize);
}
}
/**
* Prepopulates the pool with a given number of items.
* @param total - The number of items to add to the pool.
*/
prepopulate(total) {
for (let i = 0; i < total; i++) {
this._pool[this._index++] = new this._classType();
}
this._count += total;
}
/**
* Gets an item from the pool. Calls the item's `init` method if it exists.
* If there are no items left in the pool, a new one will be created.
* @param {unknown} [data] - Optional data to pass to the item's constructor.
* @returns {T} The item from the pool.
*/
get(data) {
let item;
if (this._index > 0) {
item = this._pool[--this._index];
} else {
item = new this._classType();
}
item.init?.(data);
return item;
}
/**
* Returns an item to the pool. Calls the item's `reset` method if it exists.
* @param {T} item - The item to return to the pool.
*/
return(item) {
item.reset?.();
this._pool[this._index++] = item;
}
/**
* Gets the number of items in the pool.
* @readonly
*/
get totalSize() {
return this._count;
}
/**
* Gets the number of items in the pool that are free to use without needing to create more.
* @readonly
*/
get totalFree() {
return this._index;
}
/**
* Gets the number of items in the pool that are currently in use.
* @readonly
*/
get totalUsed() {
return this._count - this._index;
}
/** clears the pool - mainly used for debugging! */
clear() {
this._pool.length = 0;
this._index = 0;
}
}
exports.Pool = Pool;
//# sourceMappingURL=Pool.js.map