clamp.cjs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. "use strict";
  2. exports.clamp = clamp;
  3. var _index = require("./_lib/normalizeDates.cjs");
  4. var _index2 = require("./max.cjs");
  5. var _index3 = require("./min.cjs");
  6. /**
  7. * The {@link clamp} function options.
  8. */
  9. /**
  10. * The {@link clamp} function result type. It resolves the proper data type.
  11. * It uses the first argument date object type, starting from the date argument,
  12. * then the start interval date, and finally the end interval date. If
  13. * a context function is passed, it uses the context function return type.
  14. */
  15. /**
  16. * @name clamp
  17. * @category Interval Helpers
  18. * @summary Return a date bounded by the start and the end of the given interval.
  19. *
  20. * @description
  21. * Clamps a date to the lower bound with the start of the interval and the upper
  22. * bound with the end of the interval.
  23. *
  24. * - When the date is less than the start of the interval, the start is returned.
  25. * - When the date is greater than the end of the interval, the end is returned.
  26. * - Otherwise the date is returned.
  27. *
  28. * @typeParam DateType - Date argument type.
  29. * @typeParam IntervalType - Interval argument type.
  30. * @typeParam Options - Options type.
  31. *
  32. * @param date - The date to be bounded
  33. * @param interval - The interval to bound to
  34. * @param options - An object with options
  35. *
  36. * @returns The date bounded by the start and the end of the interval
  37. *
  38. * @example
  39. * // What is Mar 21, 2021 bounded to an interval starting at Mar 22, 2021 and ending at Apr 01, 2021
  40. * const result = clamp(new Date(2021, 2, 21), {
  41. * start: new Date(2021, 2, 22),
  42. * end: new Date(2021, 3, 1),
  43. * })
  44. * //=> Mon Mar 22 2021 00:00:00
  45. */
  46. function clamp(date, interval, options) {
  47. const [date_, start, end] = (0, _index.normalizeDates)(
  48. options?.in,
  49. date,
  50. interval.start,
  51. interval.end,
  52. );
  53. return (0, _index3.min)(
  54. [(0, _index2.max)([date_, start], options), end],
  55. options,
  56. );
  57. }