| 26 | * //=> 1 |
| 27 | */ |
| 28 | export 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 | } |