This solution is generated by ChatGPT, correctness is not guaranteed.

AI solution for JavaScript Coding Question on BFE.dev
73. implement Observable fromEvent()

Solution:

function fromEvent(node, eventName) {
  return new Observable(function subscribe(observer) {
    function eventHandler(event) {
      observer.next(event);
    }

    node.addEventListener(eventName, eventHandler);

    return {
      unsubscribe() {
        node.removeEventListener(eventName, eventHandler);
      },
    };
  });
}

Explanation:

The fromEvent() function takes in a DOM element and an event type as input and returns an Observable. We create an Observable instance by passing a subscribe function to it. The subscribe function will be called when the Observable is subscribed to.

In the subscribe function, we attach an event listener to the DOM node using addEventListener(). The event listener callback simply calls observer.next() with the event object. Whenever the event is triggered, the Observable emits the event object using observer.next().

Finally, we return an object with an unsubscribe() method. This method is used to remove the event listener when the Observable is unsubscribed from. We do this using removeEventListener().