UNPKG

lazy-widgets

Version:

Typescript retained mode GUI for the HTML canvas API

62 lines 1.72 kB
/** * A special collection type that can be modified while being iterated. Useful * for implementing event listener lists. * * Can only add at the end of the collection, but can remove from anywhere in * the collection (while iterating). Preserves insertion order. */ export class ConcurrentCollection { constructor() { this.iterators = new Set(); this.values = []; } indexOf(value) { return this.values.indexOf(value); } forEach(callback) { const iterator = { nextIndex: 0, endIndex: this.size, }; this.iterators.add(iterator); try { while (iterator.nextIndex < iterator.endIndex) { callback(this.values[iterator.nextIndex++]); } } finally { this.iterators.delete(iterator); } } add(value) { return this.values.push(value) - 1; } shiftBackIterators(index) { for (const iterator of this.iterators) { if (iterator.nextIndex < index) { iterator.nextIndex--; } if (index < iterator.endIndex) { iterator.endIndex--; } } } remove(index) { const removed = this.values.splice(index, 1).length > 0; this.shiftBackIterators(index); return removed; } removeByValue(value) { const index = this.indexOf(value); if (index < 0) { return false; } this.values.splice(index, 1); this.shiftBackIterators(index); return true; } get size() { return this.values.length; } } //# sourceMappingURL=ConcurrentCollection.js.map