The task is implement map(), as the name indicates, it maps the value to another value thus creating a new event stream.
The boilerplate code
function map(transform) {
// your code here
}
Think of map as a machine that sits between original event stream and new event stream. It takes a transform function and returns a new observable.
return (sourceObservable) =>
new Observable((observer) => {
}
}
When the new observable is subscribed to, it subscribes to the original observable. Every time the original observable sends a value, the value is transformed and set to the new observable.
return sourceObservable.subscribe({
next(value) {
observer.next(transform(value));
},
Errors and completion are passed through unchanged
error(err) {
observer.error(err);
},
complete() {
observer.complete();
}
So map doesn't change the original stream, it creates a new stream where each emitted value is transformed.
The final code
function map(transform) {
// your code here
return (sourceObservable) =>
new Observable((observer) => {
return sourceObservable.subscribe({
next(value) {
observer.next(transform(value));
},
error(err) {
observer.error(err);
},
complete() {
observer.complete();
}
});
});
}
That's all folks!
Top comments (0)