clamp.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import { normalizeDates } from "./_lib/normalizeDates.js";
  2. import { max } from "./max.js";
  3. import { min } from "./min.js";
  4. /**
  5. * The {@link clamp} function options.
  6. */
  7. /**
  8. * The {@link clamp} 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 clamp
  15. * @category Interval Helpers
  16. * @summary Return a date bounded by the start and the end of the given interval.
  17. *
  18. * @description
  19. * Clamps a date to the lower bound with the start of the interval and the upper
  20. * bound with the end of the interval.
  21. *
  22. * - When the date is less than the start of the interval, the start is returned.
  23. * - When the date is greater than the end of the interval, the end is returned.
  24. * - Otherwise the date is returned.
  25. *
  26. * @typeParam DateType - Date argument type.
  27. * @typeParam IntervalType - Interval argument type.
  28. * @typeParam Options - Options type.
  29. *
  30. * @param date - The date to be bounded
  31. * @param interval - The interval to bound to
  32. * @param options - An object with options
  33. *
  34. * @returns The date bounded by the start and the end of the interval
  35. *
  36. * @example
  37. * // What is Mar 21, 2021 bounded to an interval starting at Mar 22, 2021 and ending at Apr 01, 2021
  38. * const result = clamp(new Date(2021, 2, 21), {
  39. * start: new Date(2021, 2, 22),
  40. * end: new Date(2021, 3, 1),
  41. * })
  42. * //=> Mon Mar 22 2021 00:00:00
  43. */
  44. export function clamp(date, interval, options) {
  45. const [date_, start, end] = normalizeDates(
  46. options?.in,
  47. date,
  48. interval.start,
  49. interval.end,
  50. );
  51. return min([max([date_, start], options), end], options);
  52. }
  53. // Fallback for modularized imports:
  54. export default clamp;