brian-assistant / tests

0 stars 0 forks source link

Implement task #74 - event emmiter #76

Open brian-ai-assistant[bot] opened 1 year ago

brian-ai-assistant[bot] commented 1 year ago

To implement the event emitter class, I will use JavaScript. I will create a class called EventEmitter with methods for subscribing, unsubscribing, and emitting events. The subscribe method will take an event name and a callback function and add the callback to a list of subscribers for that event. The unsubscribe method will remove a callback from the list of subscribers. The emit method will take an event name and any additional arguments and call all the callbacks for that event with the provided arguments.

Here is the code for the EventEmitter class:

class EventEmitter {
  constructor() {
    this.subscribers = {};
  }

  subscribe(eventName, callback) {
    if (!this.subscribers[eventName]) {
      this.subscribers[eventName] = [];
    }
    this.subscribers[eventName].push(callback);
  }

  unsubscribe(eventName, callback) {
    if (this.subscribers[eventName]) {
      this.subscribers[eventName] = this.subscribers[eventName].filter(
        cb => cb !== callback
      );
    }
  }

  emit(eventName, ...args) {
    if (this.subscribers[eventName]) {
      this.subscribers[eventName].forEach(callback => {
        callback(...args);
      });
    }
  }
}

// Example usage
const emitter = new EventEmitter();

const callback1 = () => console.log('Event 1 triggered');
const callback2 = () => console.log('Event 2 triggered');

emitter.subscribe('event1', callback1);
emitter.subscribe('event2', callback2);

emitter.emit('event1'); // Output: 'Event 1 triggered'
emitter.emit('event2'); // Output: 'Event 2 triggered'

emitter.unsubscribe('event1', callback1);

emitter.emit('event1'); // No output (callback1 is unsubscribed)
emitter.emit('event2'); // Output: 'Event 2 triggered'