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
71. implement Observable Subject
class Subject { constructor() { this.observers = []; } subscribe(observer) { this.observers.push(observer); } next(value) { this.observers.forEach(observer => observer.next(value)); } error(error) { this.observers.forEach(observer => observer.error(error)); } complete() { this.observers.forEach(observer => observer.complete()); }}
Explanation:
- We define a class called
Subject. - In the constructor, we initialize an empty array called
observersto hold all the observers subscribed to the subject. - We define a method
subscribeto add an observer to theobserversarray. - We define a method
nextto dispatch the next value to all the observers in theobserversarray. - We define a method
errorto dispatch an error to all the observers in theobserversarray. - We define a method
completeto signal the completion of the observable to all the observers in theobserversarray.