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
observers
to hold all the observers subscribed to the subject. - We define a method
subscribe
to add an observer to theobservers
array. - We define a method
next
to dispatch the next value to all the observers in theobservers
array. - We define a method
error
to dispatch an error to all the observers in theobservers
array. - We define a method
complete
to signal the completion of the observable to all the observers in theobservers
array.