Skip to content

Instantly share code, notes, and snippets.

@guiseek
Last active February 29, 2024 17:24
Show Gist options
  • Save guiseek/649b3f29fd96edcb5da5911206469a52 to your computer and use it in GitHub Desktop.
Save guiseek/649b3f29fd96edcb5da5911206469a52 to your computer and use it in GitHub Desktop.
custom rxjs
// Exemplo de uso:
of(10)
.pipe(
map((value) => value * 4),
filter((value) => value > 2)
)
.subscribe((value) => console.log(value));
function filter<T>(predicate: (value: T) => boolean): Operator<T, T | null> {
return (source: T) => (predicate(source) ? source : null);
}
function map<T, R>(transform: (value: T) => R): Operator<T, R> {
return (source: T) => transform(source);
}
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>;
}
}
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