UNPKG

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