Created
June 21, 2017 17:02
-
-
Save jelbourn/cce9d4f64eb584f0a25e9a929d335155 to your computer and use it in GitHub Desktop.
Chaining rxjs operators without modifying the prototype with type enforcement
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
export declare class MapBrand { private _x; } | |
export declare class FilterBrand { private _x; } | |
export declare class ReduceBrand { private _x; } | |
export type mapOperator<T, R> = typeof map & MapBrand; | |
export type filterOperator<T> = typeof filter & FilterBrand; | |
export type reduceOperator<T> = typeof reduce & ReduceBrand; | |
const myMap = map as typeof map & MapBrand; | |
const myFilter = filter as typeof filter & FilterBrand; | |
const myReduce = reduce as typeof reduce & ReduceBrand; | |
export interface StrictRxChain<T> { | |
call(operator: filterOperator<T>, predicate: (value: T, index: number) => boolean, thisArg?: any): StrictRxChain<T>; | |
call<R>(operator: mapOperator<T, R>, project: (value: T, index: number) => R, thisArg?: any): StrictRxChain<R>; | |
call(operator: reduceOperator<T>, accumulator: (acc: T, value: T, index: number) => T, seed?: T): StrictRxChain<T>; | |
subscribe(fn: (t: T) => void): Subscription; | |
result(): Observable<T>; | |
} | |
export class RxChain<T> { | |
constructor(private _context: Observable<T>) { } | |
static from<T>(context: Observable<T>): StrictRxChain<T> { | |
return new RxChain(context); | |
} | |
call(operator: Function, fn: Function, ...args: any[]): RxChain<any> { | |
this._context = operator.call(this._context, fn, ...args); | |
return this; | |
} | |
subscribe(fn: (t: T) => void): Subscription { | |
return this._context.subscribe(fn); | |
} | |
result(): Observable<T> { | |
return this._context; | |
} | |
} | |
let numbers: Observable<number> = from([1, 2, 3, 4, 5, 6, 7, 8]); | |
let numberResult: Observable<number>; | |
numberResult = RxChain.from(numbers) | |
.call(myMap, i => i + 1) | |
.call(myFilter, i => !!i) | |
.call(myReduce, (i, t) => i + t, 0) | |
.result(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment