pairwise.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import { Subscriber } from '../Subscriber';
  2. /**
  3. * Groups pairs of consecutive emissions together and emits them as an array of
  4. * two values.
  5. *
  6. * <span class="informal">Puts the current value and previous value together as
  7. * an array, and emits that.</span>
  8. *
  9. * <img src="./img/pairwise.png" width="100%">
  10. *
  11. * The Nth emission from the source Observable will cause the output Observable
  12. * to emit an array [(N-1)th, Nth] of the previous and the current value, as a
  13. * pair. For this reason, `pairwise` emits on the second and subsequent
  14. * emissions from the source Observable, but not on the first emission, because
  15. * there is no previous value in that case.
  16. *
  17. * @example <caption>On every click (starting from the second), emit the relative distance to the previous click</caption>
  18. * var clicks = Rx.Observable.fromEvent(document, 'click');
  19. * var pairs = clicks.pairwise();
  20. * var distance = pairs.map(pair => {
  21. * var x0 = pair[0].clientX;
  22. * var y0 = pair[0].clientY;
  23. * var x1 = pair[1].clientX;
  24. * var y1 = pair[1].clientY;
  25. * return Math.sqrt(Math.pow(x0 - x1, 2) + Math.pow(y0 - y1, 2));
  26. * });
  27. * distance.subscribe(x => console.log(x));
  28. *
  29. * @see {@link buffer}
  30. * @see {@link bufferCount}
  31. *
  32. * @return {Observable<Array<T>>} An Observable of pairs (as arrays) of
  33. * consecutive values from the source Observable.
  34. * @method pairwise
  35. * @owner Observable
  36. */
  37. export function pairwise() {
  38. return (source) => source.lift(new PairwiseOperator());
  39. }
  40. class PairwiseOperator {
  41. call(subscriber, source) {
  42. return source.subscribe(new PairwiseSubscriber(subscriber));
  43. }
  44. }
  45. /**
  46. * We need this JSDoc comment for affecting ESDoc.
  47. * @ignore
  48. * @extends {Ignored}
  49. */
  50. class PairwiseSubscriber extends Subscriber {
  51. constructor(destination) {
  52. super(destination);
  53. this.hasPrev = false;
  54. }
  55. _next(value) {
  56. if (this.hasPrev) {
  57. this.destination.next([this.prev, value]);
  58. }
  59. else {
  60. this.hasPrev = true;
  61. }
  62. this.prev = value;
  63. }
  64. }
  65. //# sourceMappingURL=pairwise.js.map