clamp.mjs 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. import { max } from "./max.mjs";
  2. import { min } from "./min.mjs";
  3. /**
  4. * @name clamp
  5. * @category Interval Helpers
  6. * @summary Return a date bounded by the start and the end of the given interval
  7. *
  8. * @description
  9. * Clamps a date to the lower bound with the start of the interval and the upper
  10. * bound with the end of the interval.
  11. *
  12. * - When the date is less than the start of the interval, the start is returned.
  13. * - When the date is greater than the end of the interval, the end is returned.
  14. * - Otherwise the date is returned.
  15. *
  16. * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
  17. *
  18. * @param date - The date to be bounded
  19. * @param interval - The interval to bound to
  20. *
  21. * @returns The date bounded by the start and the end of the interval
  22. *
  23. * @example
  24. * // What is Mar, 21, 2021 bounded to an interval starting at Mar, 22, 2021 and ending at Apr, 01, 2021
  25. * const result = clamp(new Date(2021, 2, 21), {
  26. * start: new Date(2021, 2, 22),
  27. * end: new Date(2021, 3, 1),
  28. * })
  29. * //=> Mon Mar 22 2021 00:00:00
  30. */
  31. export function clamp(date, interval) {
  32. return min([max([date, interval.start]), interval.end]);
  33. }
  34. // Fallback for modularized imports:
  35. export default clamp;