closestTo.js 1.8 KB

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