closestIndexTo.cjs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. "use strict";
  2. exports.closestIndexTo = closestIndexTo;
  3. var _index = require("./toDate.cjs");
  4. /**
  5. * @name closestIndexTo
  6. * @category Common Helpers
  7. * @summary Return an index of the closest date from the array comparing to the given date.
  8. *
  9. * @description
  10. * Return an index of the closest date from the array comparing to the given date.
  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. function closestIndexTo(dateToCompare, dates) {
  29. // [TODO] It would be better to return -1 here rather than undefined, as this
  30. // is how JS behaves, but it would be a breaking change, so we need
  31. // to consider it for v4.
  32. const timeToCompare = +(0, _index.toDate)(dateToCompare);
  33. if (isNaN(timeToCompare)) return NaN;
  34. let result;
  35. let minDistance;
  36. dates.forEach((date, index) => {
  37. const date_ = (0, _index.toDate)(date);
  38. if (isNaN(+date_)) {
  39. result = NaN;
  40. minDistance = NaN;
  41. return;
  42. }
  43. const distance = Math.abs(timeToCompare - +date_);
  44. if (result == null || distance < minDistance) {
  45. result = index;
  46. minDistance = distance;
  47. }
  48. });
  49. return result;
  50. }