-
Notifications
You must be signed in to change notification settings - Fork 3k
/
Copy pathmap.ts
53 lines (44 loc) · 1.62 KB
/
map.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import {Operator} from '../Operator';
import {Subscriber} from '../Subscriber';
import {Observable} from '../Observable';
import {tryCatch} from '../util/tryCatch';
import {errorObject} from '../util/errorObject';
import {bindCallback} from '../util/bindCallback';
/**
* Similar to the well known `Array.prototype.map` function, this operator
* applies a projection to each value and emits that projection in the returned observable
*
* @param {Function} project the function to create projection
* @param {any} [thisArg] an optional argument to define what `this` is in the project function
* @returns {Observable} a observable of projected values
*/
export function map<T, R>(project: (x: T, ix?: number) => R, thisArg?: any): Observable<R> {
return this.lift(new MapOperator(project, thisArg));
}
class MapOperator<T, R> implements Operator<T, R> {
project: (x: T, ix?: number) => R;
constructor(project: (x: T, ix?: number) => R, thisArg?: any) {
this.project = <(x: T, ix?: number) => R>bindCallback(project, thisArg, 2);
}
call(subscriber: Subscriber<R>): Subscriber<T> {
return new MapSubscriber(subscriber, this.project);
}
}
class MapSubscriber<T, R> extends Subscriber<T> {
count: number = 0;
project: (x: T, ix?: number) => R;
constructor(destination: Subscriber<R>,
project: (x: T, ix?: number) => R) {
super(destination);
this.project = project;
}
_next(x) {
const result = tryCatch(this.project)(x, this.count++);
if (result === errorObject) {
this.error(errorObject.e);
} else {
this.destination.next(result);
}
}
}
Observable.prototype.map = map;