UNPKG

@cch137/emitter

Version:

`@cch137/emitter` is a versatile event emitter package designed to work seamlessly in both browser and Node.js environments. It provides a simple yet powerful interface for managing event-driven architecture in your applications.

81 lines (80 loc) 1.89 kB
export default class Group extends Array { static Group = Group; constructor(...items) { super(...items); } add(...items) { items.forEach((item) => { if (!this.has(item)) this.push(item); }); return this; } delete(item) { let found = false; for (let i = this.length - 1; i > -1; i--) { if (this[i] === item) { this.splice(i, 1); if (!found) found = true; } } return found; } deleteLast(item) { for (let i = this.length - 1; i > -1; i--) { if (this[i] === item) { this.splice(i, 1); return true; } } return false; } deleteOne(item) { const length = this.length; for (let i = 0; i < length; i++) { if (this[i] === item) { this.splice(i, 1); return true; } } return false; } has(item) { return this.includes(item); } clear() { this.splice(0); } } export { Group }; export class Collection extends Map { group(key) { if (super.has(key)) return super.get(key); const g = new Group(); return super.set(key, g), g; } once(key) { const g = super.get(key); return super.delete(key), g; } trim() { [...this].forEach(([k, g]) => { if (g.length === 0) this.delete(k); }); } } export class WeakCollection extends WeakMap { group(key) { if (super.has(key)) return super.get(key); const g = new Group(); return super.set(key, g), g; } once(key) { const g = super.get(key); return super.delete(key), g; } }