closestTo.cjs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. "use strict";
  2. exports.closestTo = closestTo;
  3. var _index = require("./_lib/normalizeDates.cjs");
  4. var _index2 = require("./closestIndexTo.cjs");
  5. var _index3 = require("./constructFrom.cjs");
  6. /**
  7. * The {@link closestTo} function options.
  8. */
  9. /**
  10. * The {@link closestTo} function result type. It resolves the proper data type.
  11. * It uses the first argument date object type, starting from the date argument,
  12. * then the start interval date, and finally the end interval date. If
  13. * a context function is passed, it uses the context function return type.
  14. */
  15. /**
  16. * @name closestTo
  17. * @category Common Helpers
  18. * @summary Return a date from the array closest to the given date.
  19. *
  20. * @description
  21. * Return a date from the array closest to the given date.
  22. *
  23. * @typeParam DateToCompare - Date to compare argument type.
  24. * @typeParam DatesType - Dates array argument type.
  25. * @typeParam Options - Options type.
  26. *
  27. * @param dateToCompare - The date to compare with
  28. * @param dates - The array to search
  29. *
  30. * @returns The date from the array closest to the given date or undefined if no valid value is given
  31. *
  32. * @example
  33. * // Which date is closer to 6 September 2015: 1 January 2000 or 1 January 2030?
  34. * const dateToCompare = new Date(2015, 8, 6)
  35. * const result = closestTo(dateToCompare, [
  36. * new Date(2000, 0, 1),
  37. * new Date(2030, 0, 1)
  38. * ])
  39. * //=> Tue Jan 01 2030 00:00:00
  40. */
  41. function closestTo(dateToCompare, dates, options) {
  42. const [dateToCompare_, ...dates_] = (0, _index.normalizeDates)(
  43. options?.in,
  44. dateToCompare,
  45. ...dates,
  46. );
  47. const index = (0, _index2.closestIndexTo)(dateToCompare_, dates_);
  48. if (typeof index === "number" && isNaN(index))
  49. return (0, _index3.constructFrom)(dateToCompare_, NaN);
  50. if (index !== undefined) return dates_[index];
  51. }