UNPKG

@limetech/lime-elements

Version:
55 lines (54 loc) 1.44 kB
export class ElementPool { constructor(document) { this.isFree = (element) => { return !this.usedElements.has(element); }; this.document = document; this.releaseAll(); this.clear(); } /** * Get an element from the pool * * @param name - tag name of the element * @returns the element */ get(name) { var _a; let element = (_a = this.pool[name]) === null || _a === void 0 ? void 0 : _a.find(this.isFree); if (!element) { element = this.createElement(name); } this.usedElements.set(element, true); return element; } /** * Release an element from the pool so that it can be reused * * @param element - the element to release from the pool */ release(element) { this.usedElements.delete(element); } /** * Release all elements from the pool so that they can be reused */ releaseAll() { this.usedElements = new WeakMap(); } /** * Remove all elements from the pool and makes them available for garbage * collection */ clear() { this.pool = {}; } createElement(name) { const element = this.document.createElement(name); if (!(name in this.pool)) { this.pool[name] = []; } this.pool[name].push(element); return element; } }