Coding Challenge Practice - Question 74
Source: Dev.to
Description
The map() operator creates a new observable by applying a transformation function to each value emitted by the original (source) observable. It does not modify the source stream; instead, it produces a new stream where every emitted value is the result of transform(value). Errors and completion notifications are passed through unchanged.
Implementation
function map(transform) {
// Returns a function that takes the source observable
// and returns a new observable applying the transformation.
return (sourceObservable) =>
new Observable((observer) => {
// Subscribe to the source observable
return sourceObservable.subscribe({
// Transform each emitted value
next(value) {
observer.next(transform(value));
},
// Forward errors unchanged
error(err) {
observer.error(err);
},
// Forward completion unchanged
complete() {
observer.complete();
}
});
});
}