This solution is generated by ChatGPT, correctness is not guaranteed. You might also be able to find a solution fromcommunity posts.
AI solution for JavaScript Coding Question on BFE.dev
16. create an Event Emitter
One possible solution for the Event Emitter Class is:
class Emitter { constructor() { this.listeners = {} } subscribe(eventName, callback) { this.listeners[eventName] = this.listeners[eventName] || [] const listener = {callback} this.listeners[eventName].push(listener) const release = () => { const index = this.listeners[eventName].indexOf(listener) this.listeners[eventName].splice(index, 1) if (this.listeners[eventName].length === 0) { delete this.listeners[eventName] } } return {release} } emit(eventName, ...args) { if (!this.listeners[eventName]) { return } for (const listener of this.listeners[eventName]) { listener.callback(...args) } }}
The Emitter
class has a listeners
property that keeps track of all the subscribed callbacks for each event. The subscribe
method takes an eventName
and a callback
, and pushes a new listener object with the callback into the appropriate array in the listeners
property. It then returns an object with a release
method that will remove the listener from the array when called.
The emit
method takes an eventName
and any number of arguments to pass to the callbacks. It checks if there are any listeners for the event, and if so, iterates over them and calls each one with the arguments passed to emit
.
Example usage:
const emitter = new Emitter()const callback1 = (a, b) => console.log(`callback1 called with ${a} and ${b}`)const callback2 = () => console.log('callback2 called')const sub1 = emitter.subscribe('event1', callback1)const sub2 = emitter.subscribe('event2', callback2)emitter.emit('event1', 1, 2)// output: "callback1 called with 1 and 2"emitter.emit('event2')// output: "callback2 called"sub1.release()emitter.emit('event1', 3, 4)// output: nothingsub2.release()emitter.emit('event2')// output: nothing