UNPKG

toosoon-utils

Version:
68 lines (67 loc) 1.58 kB
// ********************* // WIP // ********************* export const defaultSettings = { max: Infinity }; /** * Abstract class for manipulating pool items * * @exports * @class Pool */ export default class Pool { items = []; pool = []; settings = { ...defaultSettings }; constructor(settings = { ...defaultSettings }) { this.settings = Object.assign(this.settings, settings); } /** * Add an item to the active items * * @param {PoolItem} item Item to add to the active items */ add(item) { this.items.push(item); } /** * Remove an item from the active items * * @param {PoolItem} item Item to remove from the active items */ remove(item) { this.items = this.items.filter((_item) => _item !== item); } /** * Return an item from pool or create a new one * * @returns {PoolItem|undefined} */ get() { if (this.items.length >= this.settings.max) return; const item = this.pool.pop() ?? this.create(); item.setup?.(); this.add(item); return item; } /** * Release an item from the active items and add it to the pool * * @param {PoolItem} item Item to release */ release(item) { this.pool.push(item); item.reset?.(); this.remove(item); } /** * Dispose all items */ dispose() { [...this.items, ...this.pool].forEach((item) => item.dispose?.()); this.items = []; this.pool = []; } }