Debian Codegraph @

node/rxjs/src/internal/operators/count.ts

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