Debian Codegraph @

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

raw
1 import { reduce } from './reduce';
2 import { MonoTypeOperatorFunction } from '../types';
3 import { isFunction } from '../util/isFunction';
4
5 /**
6 * The `max` operator operates on an Observable that emits numbers (or items that
7 * can be compared with a provided function), and when source Observable completes
8 * it emits a single item: the item with the largest value.
9 *
10 * ![](max.png)
11 *
12 * ## Examples
13 *
14 * Get the maximal value of a series of numbers
15 *
16 * ```ts
17 * import { of, max } from 'rxjs';
18 *
19 * of(5, 4, 7, 2, 8)
20 * .pipe(max())
21 * .subscribe(x => console.log(x));
22 *
23 * // Outputs
24 * // 8
25 * ```
26 *
27 * Use a comparer function to get the maximal item
28 *
29 * ```ts
30 * import { of, max } from 'rxjs';
31 *
32 * of(
33 * { age: 7, name: 'Foo' },
34 * { age: 5, name: 'Bar' },
35 * { age: 9, name: 'Beer' }
36 * ).pipe(
37 * max((a, b) => a.age < b.age ? -1 : 1)
38 * )
39 * .subscribe(x => console.log(x.name));
40 *
41 * // Outputs
42 * // 'Beer'
43 * ```
44 *
45 * @see {@link min}
46 *
47 * @param comparer Optional comparer function that it will use instead of its
48 * default to compare the value of two items.
49 * @return A function that returns an Observable that emits item with the
50 * largest value.
51 */
52 export function max<T>(comparer?: (x: T, y: T) => number): MonoTypeOperatorFunction<T> {
53 return reduce(isFunction(comparer) ? (x, y) => (comparer(x, y) > 0 ? x : y) : (x, y) => (x > y ? x : y));
54 }