Repositorio del curso CCOM4030 el semestre B91 del proyecto Artesanías con el Instituto de Cultura

max.ts 1.5KB

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