index.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435
  1. import max from "../max/index.js";
  2. import min from "../min/index.js";
  3. import requiredArgs from "../_lib/requiredArgs/index.js";
  4. /**
  5. * @name clamp
  6. * @category Interval Helpers
  7. * @summary Return a date bounded by the start and the end of the given interval
  8. *
  9. * @description
  10. * Clamps a date to the lower bound with the start of the interval and the upper
  11. * bound with the end of the interval.
  12. *
  13. * - When the date is less than the start of the interval, the start is returned.
  14. * - When the date is greater than the end of the interval, the end is returned.
  15. * - Otherwise the date is returned.
  16. *
  17. * @example
  18. * // What is Mar, 21, 2021 bounded to an interval starting at Mar, 22, 2021 and ending at Apr, 01, 2021
  19. * const result = clamp(new Date(2021, 2, 21), {
  20. * start: new Date(2021, 2, 22),
  21. * end: new Date(2021, 3, 1),
  22. * })
  23. * //=> Mon Mar 22 2021 00:00:00
  24. *
  25. * @param {Date | Number} date - the date to be bounded
  26. * @param {Interval} interval - the interval to bound to
  27. * @returns {Date} the date bounded by the start and the end of the interval
  28. * @throws {TypeError} 2 arguments required
  29. */
  30. export default function clamp(date, _ref) {
  31. var start = _ref.start,
  32. end = _ref.end;
  33. requiredArgs(2, arguments);
  34. return min([max([date, start]), end]);
  35. }