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