clamp.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. "use strict";
  2. exports.clamp = clamp;
  3. var _index = require("./max.js");
  4. var _index2 = require("./min.js");
  5. /**
  6. * @name clamp
  7. * @category Interval Helpers
  8. * @summary Return a date bounded by the start and the end of the given interval
  9. *
  10. * @description
  11. * Clamps a date to the lower bound with the start of the interval and the upper
  12. * bound with the end of the interval.
  13. *
  14. * - When the date is less than the start of the interval, the start is returned.
  15. * - When the date is greater than the end of the interval, the end is returned.
  16. * - Otherwise the date is returned.
  17. *
  18. * @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).
  19. *
  20. * @param date - The date to be bounded
  21. * @param interval - The interval to bound to
  22. *
  23. * @returns The date bounded by the start and the end of the interval
  24. *
  25. * @example
  26. * // What is Mar, 21, 2021 bounded to an interval starting at Mar, 22, 2021 and ending at Apr, 01, 2021
  27. * const result = clamp(new Date(2021, 2, 21), {
  28. * start: new Date(2021, 2, 22),
  29. * end: new Date(2021, 3, 1),
  30. * })
  31. * //=> Mon Mar 22 2021 00:00:00
  32. */
  33. function clamp(date, interval) {
  34. return (0, _index2.min)([
  35. (0, _index.max)([date, interval.start]),
  36. interval.end,
  37. ]);
  38. }