UNPKG

@mousepox/util

Version:

Miscellaneous utilities

66 lines (65 loc) 1.54 kB
import { Signal } from "./Signal"; export class Collection { constructor() { this.onAdd = new Signal(); this.onRemove = new Signal(); this.things = new Map(); } get size() { return this.things.size; } clear() { this.things.clear(); } dispose() { this.onAdd.purge(); this.onRemove.purge(); this.clear(); } add(key, thing) { this.things.set(key, thing); this.onAdd.emit(thing); } remove(key) { const thing = this.things.get(key); if (thing !== undefined) { this.things.delete(key); this.onRemove.emit(thing); } } get(key) { return this.things.get(key); } each(fn, filter) { for (const [key, thing] of this.things) { if (filter === undefined || filter(thing)) { fn(thing, key); } } } count(filter) { let count = 0; for (const [, thing] of this.things) { if (filter(thing)) { count++; } } return count; } filter(filter) { const things = []; for (const [, thing] of this.things) { if (filter === undefined || filter(thing)) { things.push(thing); } } return things; } first(filter) { for (const [, thing] of this.things) { if (filter(thing)) { return thing; } } } }