b0c26ab2575767986e02a9512bbd8753a4fdd5934ebb24c1c7806cc42f6a557a4fbeb76b0b704490ad2946a774f845ea092582d58ce24794d45795d3a19cfd 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import { OperatorFunction } from '../types';
  2. import { reduce } from './reduce';
  3. /**
  4. * Counts the number of emissions on the source and emits that number when the
  5. * source completes.
  6. *
  7. * <span class="informal">Tells how many values were emitted, when the source
  8. * completes.</span>
  9. *
  10. * ![](count.png)
  11. *
  12. * `count` transforms an Observable that emits values into an Observable that
  13. * emits a single value that represents the number of values emitted by the
  14. * source Observable. If the source Observable terminates with an error, `count`
  15. * will pass this error notification along without emitting a value first. If
  16. * the source Observable does not terminate at all, `count` will neither emit
  17. * a value nor terminate. This operator takes an optional `predicate` function
  18. * as argument, in which case the output emission will represent the number of
  19. * source values that matched `true` with the `predicate`.
  20. *
  21. * ## Examples
  22. *
  23. * Counts how many seconds have passed before the first click happened
  24. *
  25. * ```ts
  26. * import { interval, fromEvent, takeUntil, count } from 'rxjs';
  27. *
  28. * const seconds = interval(1000);
  29. * const clicks = fromEvent(document, 'click');
  30. * const secondsBeforeClick = seconds.pipe(takeUntil(clicks));
  31. * const result = secondsBeforeClick.pipe(count());
  32. * result.subscribe(x => console.log(x));
  33. * ```
  34. *
  35. * Counts how many odd numbers are there between 1 and 7
  36. *
  37. * ```ts
  38. * import { range, count } from 'rxjs';
  39. *
  40. * const numbers = range(1, 7);
  41. * const result = numbers.pipe(count(i => i % 2 === 1));
  42. * result.subscribe(x => console.log(x));
  43. * // Results in:
  44. * // 4
  45. * ```
  46. *
  47. * @see {@link max}
  48. * @see {@link min}
  49. * @see {@link reduce}
  50. *
  51. * @param predicate A function that is used to analyze the value and the index and
  52. * determine whether or not to increment the count. Return `true` to increment the count,
  53. * and return `false` to keep the count the same.
  54. * If the predicate is not provided, every value will be counted.
  55. * @return A function that returns an Observable that emits one number that
  56. * represents the count of emissions.
  57. */
  58. export function count<T>(predicate?: (value: T, index: number) => boolean): OperatorFunction<T, number> {
  59. return reduce((total, value, i) => (!predicate || predicate(value, i) ? total + 1 : total), 0);
  60. }