Created
February 28, 2020 15:09
-
-
Save samoshkin/20afeb80e2e70bcc460ab1f5a2e52444 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type Operator<TSource, TTarget> = (source: Observable<TSource>) => Observable<TTarget>; | |
function pipe(this: Observable<any>, ...operators: Operator<any, any>[]): Observable<any> { | |
return operators.reduce((acc, curr) => curr(acc), this); | |
} | |
// replace native pipe() method | |
Observable.prototype.pipe = pipe; | |
function map<TSource, TTarget>(transform: (TSource) => TTarget): Operator<TSource, TTarget> { | |
return function(upstream) { | |
return new Observable(subscriber => { | |
return upstream.subscribe({ | |
next(value) { subscriber.next(transform(value)); }, | |
complete() { subscriber.complete(); }, | |
error(err) { subscriber.error(err); } | |
}); | |
}); | |
}; | |
} | |
function filter<TSource>(predicate: (TSource) => boolean): Operator<TSource, TSource> { | |
return function(upstream) { | |
return new Observable(subscriber => { | |
return upstream.subscribe({ | |
next(value) { | |
if (predicate(value)) { | |
subscriber.next(value); | |
} | |
}, | |
complete() { subscriber.complete(); }, | |
error(err) { subscriber.error(err); } | |
}); | |
}); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment