Debian Codegraph @

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

raw
1 import { OperatorFunction } from '../types';
2 import { operate } from '../util/lift';
3 import { createOperatorSubscriber } from './OperatorSubscriber';
4
5 /**
6 * Groups pairs of consecutive emissions together and emits them as an array of
7 * two values.
8 *
9 * <span class="informal">Puts the current value and previous value together as
10 * an array, and emits that.</span>
11 *
12 * ![](pairwise.png)
13 *
14 * The Nth emission from the source Observable will cause the output Observable
15 * to emit an array [(N-1)th, Nth] of the previous and the current value, as a
16 * pair. For this reason, `pairwise` emits on the second and subsequent
17 * emissions from the source Observable, but not on the first emission, because
18 * there is no previous value in that case.
19 *
20 * ## Example
21 *
22 * On every click (starting from the second), emit the relative distance to the previous click
23 *
24 * ```ts
25 * import { fromEvent, pairwise, map } from 'rxjs';
26 *
27 * const clicks = fromEvent<PointerEvent>(document, 'click');
28 * const pairs = clicks.pipe(pairwise());
29 * const distance = pairs.pipe(
30 * map(([first, second]) => {
31 * const x0 = first.clientX;
32 * const y0 = first.clientY;
33 * const x1 = second.clientX;
34 * const y1 = second.clientY;
35 * return Math.sqrt(Math.pow(x0 - x1, 2) + Math.pow(y0 - y1, 2));
36 * })
37 * );
38 *
39 * distance.subscribe(x => console.log(x));
40 * ```
41 *
42 * @see {@link buffer}
43 * @see {@link bufferCount}
44 *
45 * @return A function that returns an Observable of pairs (as arrays) of
46 * consecutive values from the source Observable.
47 */
48 export function pairwise<T>(): OperatorFunction<T, [T, T]> {
49 return operate((source, subscriber) => {
50 let prev: T;
51 let hasPrev = false;
52 source.subscribe(
53 createOperatorSubscriber(subscriber, (value) => {
54 const p = prev;
55 prev = value;
56 hasPrev && subscriber.next([p, value]);
57 hasPrev = true;
58 })
59 );
60 });
61 }