AI solution for JavaScript Coding Question on BFE.dev
70. implement Observable.from()
Solution:
Observable.from = function (input) { return new Observable(function (observer) { if (Array.isArray(input)) { input.forEach(observer.next.bind(observer)); observer.complete(); } else if (input.then && typeof input.then === 'function') { input .then(function (result) { observer.next(result); observer.complete(); }) .catch(observer.error.bind(observer)); } else if (input[Symbol.iterator]) { const iterator = input[Symbol.iterator](); let result = iterator.next(); while (!result.done) { observer.next(result.value); result = iterator.next(); } observer.complete(); } else if (input[Symbol.observable]) { if (input.subscribe && typeof input.subscribe === 'function') { return input.subscribe(observer); } const obs = input[Symbol.observable](); if (obs.subscribe && typeof obs.subscribe === 'function') { return obs.subscribe(observer); } } else { observer.error('Invalid input'); } });};
Explanation:
We have created an Observable.from
static method which accepts various types of input values and returns an Observable. The Observable is created after checking the type of the input value and its available properties.
-
If the input value is an array, we loop through the elements using forEach and emit each value using
observer.next()
. Finally, we emitobserver.complete()
to indicate completion of the Observable. -
If the input value is a Promise, we wait for the Promise to resolve using
.then()
and emit the resolved value usingobserver.next()
. If the Promise rejects, we emit the error usingobserver.error()
. -
If the input value is an iterable, we get its iterator using
[Symbol.iterator]()
and loop through the elements usingwhile
loop. We emit each value usingobserver.next()
. Finally, we emitobserver.complete()
to indicate completion of the Observable. -
If the input value is an Observable instance, we check if it has
subscribe()
method. If yes, we callsubscribe()
method and pass the observer to it. Otherwise, we get the Observable fromSymbol.observable
property and call itssubscribe()
method with the observer. -
If none of the above conditions match, we emit an error using
observer.error()
.
Note: In real-world, we should check the validity of Symbol.observable
using typeof input[Symbol.observable] === 'function'
.