Debian Codegraph @

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

raw
1 import { reduce } from './reduce';
2 import { MonoTypeOperatorFunction } from '../types';
3 import { isFunction } from '../util/isFunction';
4
5 /**
6 * The `min` 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 smallest value.
9 *
10 * ![](min.png)
11 *
12 * ## Examples
13 *
14 * Get the minimal value of a series of numbers
15 *
16 * ```ts
17 * import { of, min } from 'rxjs';
18 *
19 * of(5, 4, 7, 2, 8)
20 * .pipe(min())
21 * .subscribe(x => console.log(x));
22 *
23 * // Outputs
24 * // 2
25 * ```
26 *
27 * Use a comparer function to get the minimal item
28 *
29 * ```ts
30 * import { of, min } from 'rxjs';
31 *
32 * of(
33 * { age: 7, name: 'Foo' },
34 * { age: 5, name: 'Bar' },
35 * { age: 9, name: 'Beer' }
36 * ).pipe(
37 * min((a, b) => a.age < b.age ? -1 : 1)
38 * )
39 * .subscribe(x => console.log(x.name));
40 *
41 * // Outputs
42 * // 'Bar'
43 * ```
44 *
45 * @see {@link max}
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 * smallest value.
51 */
52 export function min<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 }