9871d47eec4fa6fe56bcdba7115f5611c0acf9087a85b113d4998dc87b87e9a348e5475d2e85cbee52bb3cff24f2335bae35ba9e46b020ec00f0c8c6e6d54e 1.4 KB

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