Debian Codegraph @

node/rxjs/src/internal/operators/map.ts

raw
1 import { OperatorFunction } from '../types';
2 import { operate } from '../util/lift';
3 import { createOperatorSubscriber } from './OperatorSubscriber';
4
5 export function map<T, R>(project: (value: T, index: number) => R): OperatorFunction<T, R>;
6 /** @deprecated Use a closure instead of a `thisArg`. Signatures accepting a `thisArg` will be removed in v8. */
7 export function map<T, R, A>(project: (this: A, value: T, index: number) => R, thisArg: A): OperatorFunction<T, R>;
8
9 /**
10 * Applies a given `project` function to each value emitted by the source
11 * Observable, and emits the resulting values as an Observable.
12 *
13 * <span class="informal">Like [Array.prototype.map()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map),
14 * it passes each source value through a transformation function to get
15 * corresponding output values.</span>
16 *
17 * ![](map.png)
18 *
19 * Similar to the well known `Array.prototype.map` function, this operator
20 * applies a projection to each value and emits that projection in the output
21 * Observable.
22 *
23 * ## Example
24 *
25 * Map every click to the `clientX` position of that click
26 *
27 * ```ts
28 * import { fromEvent, map } from 'rxjs';
29 *
30 * const clicks = fromEvent<PointerEvent>(document, 'click');
31 * const positions = clicks.pipe(map(ev => ev.clientX));
32 *
33 * positions.subscribe(x => console.log(x));
34 * ```
35 *
36 * @see {@link mapTo}
37 * @see {@link pluck}
38 *
39 * @param project The function to apply to each `value` emitted by the source
40 * Observable. The `index` parameter is the number `i` for the i-th emission
41 * that has happened since the subscription, starting from the number `0`.
42 * @param thisArg An optional argument to define what `this` is in the
43 * `project` function.
44 * @return A function that returns an Observable that emits the values from the
45 * source Observable transformed by the given `project` function.
46 */
47 export function map<T, R>(project: (value: T, index: number) => R, thisArg?: any): OperatorFunction<T, R> {
48 return operate((source, subscriber) => {
49 // The index of the value from the source. Used with projection.
50 let index = 0;
51 // Subscribe to the source, all errors and completions are sent along
52 // to the consumer.
53 source.subscribe(
54 createOperatorSubscriber(subscriber, (value: T) => {
55 // Call the projection function with the appropriate this context,
56 // and send the resulting value to the consumer.
57 subscriber.next(project.call(thisArg, value, index++));
58 })
59 );
60 });
61 }