UNPKG

1.2 kBJavaScriptView Raw
1import { toDate } from "./toDate.js";
2
3/**
4 * @name compareAsc
5 * @category Common Helpers
6 * @summary Compare the two dates and return -1, 0 or 1.
7 *
8 * @description
9 * Compare the two dates and return 1 if the first date is after the second,
10 * -1 if the first date is before the second or 0 if dates are equal.
11 *
12 * @param dateLeft - The first date to compare
13 * @param dateRight - The second date to compare
14 *
15 * @returns The result of the comparison
16 *
17 * @example
18 * // Compare 11 February 1987 and 10 July 1989:
19 * const result = compareAsc(new Date(1987, 1, 11), new Date(1989, 6, 10))
20 * //=> -1
21 *
22 * @example
23 * // Sort the array of dates:
24 * const result = [
25 * new Date(1995, 6, 2),
26 * new Date(1987, 1, 11),
27 * new Date(1989, 6, 10)
28 * ].sort(compareAsc)
29 * //=> [
30 * // Wed Feb 11 1987 00:00:00,
31 * // Mon Jul 10 1989 00:00:00,
32 * // Sun Jul 02 1995 00:00:00
33 * // ]
34 */
35export function compareAsc(dateLeft, dateRight) {
36 const diff = +toDate(dateLeft) - +toDate(dateRight);
37
38 if (diff < 0) return -1;
39 else if (diff > 0) return 1;
40
41 // Return 0 if diff is 0; return NaN if diff is NaN
42 return diff;
43}
44
45// Fallback for modularized imports:
46export default compareAsc;