UNPKG

1.06 kBJavaScriptView Raw
1import { toDate } from "./toDate.mjs";
2
3/**
4 * @name max
5 * @category Common Helpers
6 * @summary Return the latest of the given dates.
7 *
8 * @description
9 * Return the latest of the given dates.
10 *
11 * @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).
12 *
13 * @param dates - The dates to compare
14 *
15 * @returns The latest of the dates
16 *
17 * @example
18 * // Which of these dates is the latest?
19 * const result = max([
20 * new Date(1989, 6, 10),
21 * new Date(1987, 1, 11),
22 * new Date(1995, 6, 2),
23 * new Date(1990, 0, 1)
24 * ])
25 * //=> Sun Jul 02 1995 00:00:00
26 */
27export function max(dates) {
28 let result;
29 dates.forEach(function (dirtyDate) {
30 const currentDate = toDate(dirtyDate);
31
32 if (
33 result === undefined ||
34 result < currentDate ||
35 isNaN(Number(currentDate))
36 ) {
37 result = currentDate;
38 }
39 });
40
41 return result || new Date(NaN);
42}
43
44// Fallback for modularized imports:
45export default max;