1 import { Operator } from '../Operator';
2 import { Subscriber } from '../Subscriber';
3 import { Observable } from '../Observable';
4 import { OperatorFunction } from '../types';
7 * Applies a given `project` function to each value emitted by the source
8 * Observable, and emits the resulting values as an Observable.
10 * <span class="informal">Like [Array.prototype.map()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map),
11 * it passes each source value through a transformation function to get
12 * corresponding output values.</span>
16 * Similar to the well known `Array.prototype.map` function, this operator
17 * applies a projection to each value and emits that projection in the output
21 * Map every click to the clientX position of that click
23 * import { fromEvent } from 'rxjs';
24 * import { map } from 'rxjs/operators';
26 * const clicks = fromEvent(document, 'click');
27 * const positions = clicks.pipe(map(ev => ev.clientX));
28 * positions.subscribe(x => console.log(x));
34 * @param {function(value: T, index: number): R} project The function to apply
35 * to each `value` emitted by the source Observable. The `index` parameter is
36 * the number `i` for the i-th emission that has happened since the
37 * subscription, starting from the number `0`.
38 * @param {any} [thisArg] An optional argument to define what `this` is in the
40 * @return {Observable<R>} An Observable that emits the values from the source
41 * Observable transformed by the given `project` function.
45 export function map<T, R>(project: (value: T, index: number) => R, thisArg?: any): OperatorFunction<T, R> {
46 return function mapOperation(source: Observable<T>): Observable<R> {
47 if (typeof project !== 'function') {
48 throw new TypeError('argument is not a function. Are you looking for `mapTo()`?');
50 return source.lift(new MapOperator(project, thisArg));
54 export class MapOperator<T, R> implements Operator<T, R> {
55 constructor(private project: (value: T, index: number) => R, private thisArg: any) {
58 call(subscriber: Subscriber<R>, source: any): any {
59 return source.subscribe(new MapSubscriber(subscriber, this.project, this.thisArg));
64 * We need this JSDoc comment for affecting ESDoc.
68 class MapSubscriber<T, R> extends Subscriber<T> {
72 constructor(destination: Subscriber<R>,
73 private project: (value: T, index: number) => R,
76 this.thisArg = thisArg || this;
79 // NOTE: This looks unoptimized, but it's actually purposefully NOT
80 // using try/catch optimizations.
81 protected _next(value: T) {
84 result = this.project.call(this.thisArg, value, this.count++);
86 this.destination.error(err);
89 this.destination.next(result);