Code coverage report for src/operator/pairwise.ts

Statements: 100% (19 / 19)      Branches: 100% (2 / 2)      Functions: 100% (6 / 6)      Lines: 100% (17 / 17)      Ignored: none     

All files » src/operator/ » pairwise.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42    1                     1 6     2 1 6   1   1   6   1 6     1 11 8   3     11   1  
import {Operator} from '../Operator';
import {Observable} from '../Observable';
import {Subscriber} from '../Subscriber';
 
/**
 * Returns a new observable that triggers on the second and following inputs.
 * An input that triggers an event will return an pair of [(N - 1)th, Nth].
 * The (N-1)th is stored in the internal state until Nth input occurs.
 *
 * <img src="./img/pairwise.png" width="100%">
 *
 * @returns {Observable<R>} an observable of pairs of values.
 */
export function pairwise<T>(): Observable<T> {
  return this.lift(new PairwiseOperator());
}
 
class PairwiseOperator<T, R> implements Operator<T, R> {
  call(subscriber: Subscriber<T>): Subscriber<T> {
    return new PairwiseSubscriber(subscriber);
  }
}
 
class PairwiseSubscriber<T> extends Subscriber<T> {
  private prev: T;
  private hasPrev: boolean = false;
 
  constructor(destination: Subscriber<T>) {
    super(destination);
  }
 
  _next(value: T): void {
    if (this.hasPrev) {
      this.destination.next([this.prev, value]);
    } else {
      this.hasPrev = true;
    }
 
    this.prev = value;
  }
}