1 import { Operator } from '../Operator';
2 import { Observable } from '../Observable';
3 import { Subscriber } from '../Subscriber';
4 import { OperatorFunction } from '../types';
7 * Groups pairs of consecutive emissions together and emits them as an array of
10 * <span class="informal">Puts the current value and previous value together as
11 * an array, and emits that.</span>
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.
22 * On every click (starting from the second), emit the relative distance to the previous click
24 * import { fromEvent } from 'rxjs';
25 * import { pairwise, map } from 'rxjs/operators';
27 * const clicks = fromEvent(document, 'click');
28 * const pairs = clicks.pipe(pairwise());
29 * const distance = pairs.pipe(
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));
38 * distance.subscribe(x => console.log(x));
42 * @see {@link bufferCount}
44 * @return {Observable<Array<T>>} An Observable of pairs (as arrays) of
45 * consecutive values from the source Observable.
49 export function pairwise<T>(): OperatorFunction<T, [T, T]> {
50 return (source: Observable<T>) => source.lift(new PairwiseOperator());
53 class PairwiseOperator<T> implements Operator<T, [T, T]> {
54 call(subscriber: Subscriber<[T, T]>, source: any): any {
55 return source.subscribe(new PairwiseSubscriber(subscriber));
60 * We need this JSDoc comment for affecting ESDoc.
64 class PairwiseSubscriber<T> extends Subscriber<T> {
66 private hasPrev: boolean = false;
68 constructor(destination: Subscriber<[T, T]>) {
72 _next(value: T): void {
73 let pair: [T, T] | undefined;
76 pair = [this.prev, value];
84 this.destination.next(pair);