source: trip-planner-front/node_modules/rxjs/src/internal/operators/pairwise.ts@ 8d391a1

Last change on this file since 8d391a1 was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago

initial commit

  • Property mode set to 100644
File size: 2.4 KB
Line 
1import { Operator } from '../Operator';
2import { Observable } from '../Observable';
3import { Subscriber } from '../Subscriber';
4import { OperatorFunction } from '../types';
5
6/**
7 * Groups pairs of consecutive emissions together and emits them as an array of
8 * two values.
9 *
10 * <span class="informal">Puts the current value and previous value together as
11 * an array, and emits that.</span>
12 *
13 * ![](pairwise.png)
14 *
15 * The Nth emission from the source Observable will cause the output Observable
16 * to emit an array [(N-1)th, Nth] of the previous and the current value, as a
17 * pair. For this reason, `pairwise` emits on the second and subsequent
18 * emissions from the source Observable, but not on the first emission, because
19 * there is no previous value in that case.
20 *
21 * ## Example
22 * On every click (starting from the second), emit the relative distance to the previous click
23 * ```ts
24 * import { fromEvent } from 'rxjs';
25 * import { pairwise, map } from 'rxjs/operators';
26 *
27 * const clicks = fromEvent(document, 'click');
28 * const pairs = clicks.pipe(pairwise());
29 * const distance = pairs.pipe(
30 * map(pair => {
31 * const x0 = pair[0].clientX;
32 * const y0 = pair[0].clientY;
33 * const x1 = pair[1].clientX;
34 * const y1 = pair[1].clientY;
35 * return Math.sqrt(Math.pow(x0 - x1, 2) + Math.pow(y0 - y1, 2));
36 * }),
37 * );
38 * distance.subscribe(x => console.log(x));
39 * ```
40 *
41 * @see {@link buffer}
42 * @see {@link bufferCount}
43 *
44 * @return {Observable<Array<T>>} An Observable of pairs (as arrays) of
45 * consecutive values from the source Observable.
46 * @method pairwise
47 * @owner Observable
48 */
49export function pairwise<T>(): OperatorFunction<T, [T, T]> {
50 return (source: Observable<T>) => source.lift(new PairwiseOperator());
51}
52
53class PairwiseOperator<T> implements Operator<T, [T, T]> {
54 call(subscriber: Subscriber<[T, T]>, source: any): any {
55 return source.subscribe(new PairwiseSubscriber(subscriber));
56 }
57}
58
59/**
60 * We need this JSDoc comment for affecting ESDoc.
61 * @ignore
62 * @extends {Ignored}
63 */
64class PairwiseSubscriber<T> extends Subscriber<T> {
65 private prev: T;
66 private hasPrev: boolean = false;
67
68 constructor(destination: Subscriber<[T, T]>) {
69 super(destination);
70 }
71
72 _next(value: T): void {
73 let pair: [T, T] | undefined;
74
75 if (this.hasPrev) {
76 pair = [this.prev, value];
77 } else {
78 this.hasPrev = true;
79 }
80
81 this.prev = value;
82
83 if (pair) {
84 this.destination.next(pair);
85 }
86 }
87}
Note: See TracBrowser for help on using the repository browser.