Skip to content

Instantly share code, notes, and snippets.

@siritori
Created January 17, 2021 14:58
Show Gist options
  • Save siritori/6a3258223aad85acd4f74082de484a28 to your computer and use it in GitHub Desktop.
Save siritori/6a3258223aad85acd4f74082de484a28 to your computer and use it in GitHub Desktop.
operator習作
import { strict as assert } from 'assert';
import { Operator, OperatorFunction, Subscriber } from "rxjs";
export type FilterMap<T, U> = (e: T, index: number) => U | null;
class FilterMapSubscriber<T, U> extends Subscriber<T> {
private count = 0;
private readonly thisArg: any;
constructor(
destination: Subscriber<U>,
private project: FilterMap<T, U>,
thisArg: any,
) {
super(destination);
this.thisArg = thisArg ?? this;
}
protected _next(value: T) {
let result: U | null;
try {
result = this.project.call(this.thisArg, value, this.count++);
} catch (err) {
assert(this.destination.error);
this.destination.error(err);
return;
}
if (result !== null) {
assert(this.destination.next);
this.destination.next(result);
}
}
}
class FilterMapOperator<T, U> implements Operator<T, U> {
constructor(private project: FilterMap<T, U>, private thisArg: any) {
}
call(subscriber: Subscriber<U>, source: any): any {
return source.subscribe(new FilterMapSubscriber(subscriber, this.project, this.thisArg));
}
}
export const filterMap = <T, U>(project: FilterMap<T, U>, thisArg?: any): OperatorFunction<T, U> => {
return (source) => {
return source.lift(new FilterMapOperator(project, thisArg));
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment