closestIndexTo.mjs 1.6 KB

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