partition.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. "use strict";
  2. var not_1 = require('../util/not');
  3. var filter_1 = require('./filter');
  4. /**
  5. * Splits the source Observable into two, one with values that satisfy a
  6. * predicate, and another with values that don't satisfy the predicate.
  7. *
  8. * <span class="informal">It's like {@link filter}, but returns two Observables:
  9. * one like the output of {@link filter}, and the other with values that did not
  10. * pass the condition.</span>
  11. *
  12. * <img src="./img/partition.png" width="100%">
  13. *
  14. * `partition` outputs an array with two Observables that partition the values
  15. * from the source Observable through the given `predicate` function. The first
  16. * Observable in that array emits source values for which the predicate argument
  17. * returns true. The second Observable emits source values for which the
  18. * predicate returns false. The first behaves like {@link filter} and the second
  19. * behaves like {@link filter} with the predicate negated.
  20. *
  21. * @example <caption>Partition click events into those on DIV elements and those elsewhere</caption>
  22. * var clicks = Rx.Observable.fromEvent(document, 'click');
  23. * var parts = clicks.partition(ev => ev.target.tagName === 'DIV');
  24. * var clicksOnDivs = parts[0];
  25. * var clicksElsewhere = parts[1];
  26. * clicksOnDivs.subscribe(x => console.log('DIV clicked: ', x));
  27. * clicksElsewhere.subscribe(x => console.log('Other clicked: ', x));
  28. *
  29. * @see {@link filter}
  30. *
  31. * @param {function(value: T, index: number): boolean} predicate A function that
  32. * evaluates each value emitted by the source Observable. If it returns `true`,
  33. * the value is emitted on the first Observable in the returned array, if
  34. * `false` the value is emitted on the second Observable in the array. The
  35. * `index` parameter is the number `i` for the i-th source emission that has
  36. * happened since the subscription, starting from the number `0`.
  37. * @param {any} [thisArg] An optional argument to determine the value of `this`
  38. * in the `predicate` function.
  39. * @return {[Observable<T>, Observable<T>]} An array with two Observables: one
  40. * with values that passed the predicate, and another with values that did not
  41. * pass the predicate.
  42. * @method partition
  43. * @owner Observable
  44. */
  45. function partition(predicate, thisArg) {
  46. return function (source) { return [
  47. filter_1.filter(predicate, thisArg)(source),
  48. filter_1.filter(not_1.not(predicate, thisArg))(source)
  49. ]; };
  50. }
  51. exports.partition = partition;
  52. //# sourceMappingURL=partition.js.map