closestIndexTo.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import { toDate } from "./toDate.js";
  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. * @param dateToCompare - The date to compare with
  11. * @param dates - The array to search
  12. *
  13. * @returns An index of the date closest to the given date or undefined if no valid value is given
  14. *
  15. * @example
  16. * // Which date is closer to 6 September 2015?
  17. * const dateToCompare = new Date(2015, 8, 6)
  18. * const datesArray = [
  19. * new Date(2015, 0, 1),
  20. * new Date(2016, 0, 1),
  21. * new Date(2017, 0, 1)
  22. * ]
  23. * const result = closestIndexTo(dateToCompare, datesArray)
  24. * //=> 1
  25. */
  26. export function closestIndexTo(dateToCompare, dates) {
  27. // [TODO] It would be better to return -1 here rather than undefined, as this
  28. // is how JS behaves, but it would be a breaking change, so we need
  29. // to consider it for v4.
  30. const timeToCompare = +toDate(dateToCompare);
  31. if (isNaN(timeToCompare)) return NaN;
  32. let result;
  33. let minDistance;
  34. dates.forEach((date, index) => {
  35. const date_ = toDate(date);
  36. if (isNaN(+date_)) {
  37. result = NaN;
  38. minDistance = NaN;
  39. return;
  40. }
  41. const distance = Math.abs(timeToCompare - +date_);
  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;