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