Last active
February 29, 2024 17:24
-
-
Save guiseek/649b3f29fd96edcb5da5911206469a52 to your computer and use it in GitHub Desktop.
custom rxjs
This file contains 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
// Exemplo de uso: | |
of(10) | |
.pipe( | |
map((value) => value * 4), | |
filter((value) => value > 2) | |
) | |
.subscribe((value) => console.log(value)); |
This file contains 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
function filter<T>(predicate: (value: T) => boolean): Operator<T, T | null> { | |
return (source: T) => (predicate(source) ? source : null); | |
} |
This file contains 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
function map<T, R>(transform: (value: T) => R): Operator<T, R> { | |
return (source: T) => transform(source); | |
} |
This file contains 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 Subscriber<T> = (value: T) => void; | |
type Operator<T, R> = (source: T) => R; | |
class Observable<T> { | |
constructor(private _producer: (subscriber: Subscriber<T>) => void) {} | |
subscribe(next: Subscriber<T>) { | |
this._producer(next); | |
} | |
pipe<R>(...operators: Operator<T, R>[]): Observable<R> { | |
return operators.reduce( | |
(observable, operator) => | |
new Observable((subscriber) => | |
observable.subscribe((value) => subscriber(operator(value))) | |
), | |
this as Observable<any> | |
) as Observable<R>; | |
} | |
} |
This file contains 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
function of<T>(value: T): Observable<T> { | |
return new Observable((subscriber) => subscriber(value)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment