export class EventHandler {
  constructor() {
    this.subscribers = {};
  }

  addEventListener(type, handler, { once = false } = {}) {
    if (!this.subscribers[type]) this.subscribers[type] = [];
    if (once) {
      const originalHandler = handler;
      handler = (...args) => {
        originalHandler(...args);
        this.removeEventListener(type, handler);
      };
    }
    this.subscribers[type].push(handler);
  }

  emit(type, ...data) {
    if (this.subscribers[type])
      this.subscribers[type].forEach((handler) => handler(...data));
  }

  removeEventListener(type, handler) {
    if (!this.subscribers[type]) return;
    this.subscribers[type] = this.subscribers[type].filter(
      (h) => h !== handler
    );

    if (this.subscribers[type].length === 0) {
      delete this.subscribers[type];
    }
  }
}
