max.mjs 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import { toDate } from "./toDate.mjs";
  2. /**
  3. * @name max
  4. * @category Common Helpers
  5. * @summary Return the latest of the given dates.
  6. *
  7. * @description
  8. * Return the latest of the given dates.
  9. *
  10. * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
  11. *
  12. * @param dates - The dates to compare
  13. *
  14. * @returns The latest of the dates
  15. *
  16. * @example
  17. * // Which of these dates is the latest?
  18. * const result = max([
  19. * new Date(1989, 6, 10),
  20. * new Date(1987, 1, 11),
  21. * new Date(1995, 6, 2),
  22. * new Date(1990, 0, 1)
  23. * ])
  24. * //=> Sun Jul 02 1995 00:00:00
  25. */
  26. export function max(dates) {
  27. let result;
  28. dates.forEach(function (dirtyDate) {
  29. const currentDate = toDate(dirtyDate);
  30. if (
  31. result === undefined ||
  32. result < currentDate ||
  33. isNaN(Number(currentDate))
  34. ) {
  35. result = currentDate;
  36. }
  37. });
  38. return result || new Date(NaN);
  39. }
  40. // Fallback for modularized imports:
  41. export default max;