UNPKG

lazy-widgets

Version:

Typescript retained mode GUI for the HTML canvas API

57 lines 1.6 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 }; this.iterators.add(iterator); try { while (iterator.nextIndex < this.size) { callback(this.values[iterator.nextIndex++]); } } finally { this.iterators.delete(iterator); } } add(value) { return this.values.push(value) - 1; } remove(index) { const removed = this.values.splice(index, 1).length > 0; for (const iterator of this.iterators) { if (iterator.nextIndex < index) { iterator.nextIndex--; } } return removed; } removeByValue(value) { const index = this.indexOf(value); if (index < 0) { return false; } this.values.splice(index, 1); for (const iterator of this.iterators) { if (iterator.nextIndex < index) { iterator.nextIndex--; } } return true; } get size() { return this.values.length; } } //# sourceMappingURL=ConcurrentCollection.js.map