export const defaultOpts = { initialSize: 0, maxSize: 100, create: () => {}, reset: obj => obj, free: obj => obj, collectFreq: -1 }; /** * @class ObjectPool */ export default class ObjectPool { private _opts; private _active; private _available; private _collect; private _collectInterval; /** * * @param opts */ constructor(opts:any = {}) { this._opts = {}; Object.assign(this._opts, defaultOpts); Object.assign(this._opts, opts); this._active = []; this._available = []; for(let i = 0; i < this._opts.initialSize; ++i) { this._available.push(this._opts.create()); } if(this._opts.collectFreq !== -1) { this._collect = this.collect.bind(this); this._collectInterval = setInterval(this._collect, this._opts.collectFreq); } } /** * @method collect * @private */ collect() { this._available.length = Math.min(this._available.length, this._opts.maxSize); } /** * @method get * @public * @param {any[]} args * @returns {any} */ get(...args) { const obj = this._available.length ? this._opts.reset(this._available.pop(), ...args) : this._opts.create(...args); this._active.push(obj); return obj; } freeAll() { for (let obj of this._active) { this._opts.free(obj); this._available.push(obj); } this._active.length = 0; } /** * @method free * @public * @param {any} obj */ free(obj) { const i = this._active.indexOf(obj); if(i === -1) { return; } this._opts.free(obj); this._active.splice(i, 1); this._available.push(obj); } /** * @method dispose * @public */ dispose() { clearInterval(this._collectInterval); this._active = null; this._available = null; } }