sussy-util
Version:
Util package made by me
49 lines (48 loc) • 1.47 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
class ObjectPool {
/**
* Creates an object pool.
* @param {() => T} createObjectCallback A function that creates new objects for the pool.
* @param {number} [initialPoolSize=0] The initial size of the object pool.
*/
constructor(createObjectCallback, initialPoolSize = 0) {
this.pool = [];
this.createObjectCallback = createObjectCallback;
this.populatePool(initialPoolSize);
}
/**
* Populates the object pool with a specified number of objects.
* @private
* @param {number} count The number of objects to populate.
*/
populatePool(count) {
for (let i = 0; i < count; i++) {
this.pool.push(this.createObjectCallback());
}
}
/**
* Acquires an object from the pool. If the pool is empty, a new object is created.
* @returns {T} An object from the pool or a newly created object.
*/
acquire() {
if (this.pool.length > 0) {
return this.pool.shift();
}
return this.createObjectCallback();
}
/**
* Releases an object back to the pool for reuse.
* @param {T} item The object to be released.
*/
release(item) {
this.pool.push(item);
}
/**
* Clears the object pool, removing all objects.
*/
clear() {
this.pool.length = 0;
}
}
exports.default = ObjectPool;