UNPKG

1.68 kBJavaScriptView Raw
1import { constructFrom } from "./constructFrom.mjs";
2import { toDate } from "./toDate.mjs";
3
4/**
5 * @name closestTo
6 * @category Common Helpers
7 * @summary Return a date from the array closest to the given date.
8 *
9 * @description
10 * Return a date from the array closest to the given date.
11 *
12 * @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).
13 *
14 * @param dateToCompare - The date to compare with
15 * @param dates - The array to search
16 *
17 * @returns The date from the array closest to the given date or undefined if no valid value is given
18 *
19 * @example
20 * // Which date is closer to 6 September 2015: 1 January 2000 or 1 January 2030?
21 * const dateToCompare = new Date(2015, 8, 6)
22 * const result = closestTo(dateToCompare, [
23 * new Date(2000, 0, 1),
24 * new Date(2030, 0, 1)
25 * ])
26 * //=> Tue Jan 01 2030 00:00:00
27 */
28export function closestTo(dateToCompare, dates) {
29 const date = toDate(dateToCompare);
30
31 if (isNaN(Number(date))) return constructFrom(dateToCompare, NaN);
32
33 const timeToCompare = date.getTime();
34
35 let result;
36 let minDistance;
37 dates.forEach((dirtyDate) => {
38 const currentDate = toDate(dirtyDate);
39
40 if (isNaN(Number(currentDate))) {
41 result = constructFrom(dateToCompare, NaN);
42 minDistance = NaN;
43 return;
44 }
45
46 const distance = Math.abs(timeToCompare - currentDate.getTime());
47 if (result == null || distance < minDistance) {
48 result = currentDate;
49 minDistance = distance;
50 }
51 });
52
53 return result;
54}
55
56// Fallback for modularized imports:
57export default closestTo;