min.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import { constructFrom } from "./constructFrom.js";
  2. import { toDate } from "./toDate.js";
  3. /**
  4. * The {@link min} function options.
  5. */
  6. /**
  7. * @name min
  8. * @category Common Helpers
  9. * @summary Returns the earliest of the given dates.
  10. *
  11. * @description
  12. * Returns the earliest of the given dates.
  13. *
  14. * @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).
  15. * @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.
  16. *
  17. * @param dates - The dates to compare
  18. *
  19. * @returns The earliest of the dates
  20. *
  21. * @example
  22. * // Which of these dates is the earliest?
  23. * const result = min([
  24. * new Date(1989, 6, 10),
  25. * new Date(1987, 1, 11),
  26. * new Date(1995, 6, 2),
  27. * new Date(1990, 0, 1)
  28. * ])
  29. * //=> Wed Feb 11 1987 00:00:00
  30. */
  31. export function min(dates, options) {
  32. let result;
  33. let context = options?.in;
  34. dates.forEach((date) => {
  35. // Use the first date object as the context function
  36. if (!context && typeof date === "object")
  37. context = constructFrom.bind(null, date);
  38. const date_ = toDate(date, context);
  39. if (!result || result > date_ || isNaN(+date_)) result = date_;
  40. });
  41. return constructFrom(context, result || NaN);
  42. }
  43. // Fallback for modularized imports:
  44. export default min;