MCPcopy
hub / github.com/date-fns/date-fns / closestIndexTo

Function closestIndexTo

pkgs/core/src/closestIndexTo/index.ts:28–58  ·  view source on GitHub ↗
(
  dateToCompare: DateArg<Date> & {},
  dates: Array<DateArg<Date> & {}>,
)

Source from the content-addressed store, hash-verified

26 * //=> 1
27 */
28export function closestIndexTo(
29 dateToCompare: DateArg<Date> & {},
30 dates: Array<DateArg<Date> & {}>,
31): number | undefined {
32 // [TODO] It would be better to return -1 here rather than undefined, as this
33 // is how JS behaves, but it would be a breaking change, so we need
34 // to consider it for v4.
35 const timeToCompare = +toDate(dateToCompare);
36
37 if (isNaN(timeToCompare)) return NaN;
38
39 let result: number | undefined;
40 let minDistance: number;
41 dates.forEach((date, index) => {
42 const date_ = toDate(date);
43
44 if (isNaN(+date_)) {
45 result = NaN;
46 minDistance = NaN;
47 return;
48 }
49
50 const distance = Math.abs(timeToCompare - +date_);
51 if (result == null || distance < minDistance) {
52 result = index;
53 minDistance = distance;
54 }
55 });
56
57 return result;
58}

Callers 2

test.tsFile · 0.90
closestToFunction · 0.90

Calls 1

toDateFunction · 0.90

Tested by

no test coverage detected