interval.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. "use strict";
  2. exports.interval = interval;
  3. var _index = require("./toDate.js");
  4. /**
  5. * The {@link interval} function options.
  6. */
  7. /**
  8. * @name interval
  9. * @category Interval Helpers
  10. * @summary Creates an interval object and validates its values.
  11. *
  12. * @description
  13. * Creates a normalized interval object and validates its values. If the interval is invalid, an exception is thrown.
  14. *
  15. * @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).
  16. *
  17. * @param start - The start of the interval.
  18. * @param end - The end of the interval.
  19. * @param options - The options object.
  20. *
  21. * @throws `Start date is invalid` when `start` is invalid.
  22. * @throws `End date is invalid` when `end` is invalid.
  23. * @throws `End date must be after start date` when end is before `start` and `options.assertPositive` is true.
  24. *
  25. * @returns The normalized and validated interval object.
  26. */
  27. function interval(start, end, options) {
  28. const _start = (0, _index.toDate)(start);
  29. if (isNaN(+_start)) throw new TypeError("Start date is invalid");
  30. const _end = (0, _index.toDate)(end);
  31. if (isNaN(+_end)) throw new TypeError("End date is invalid");
  32. if (options?.assertPositive && +_start > +_end)
  33. throw new TypeError("End date must be after start date");
  34. return { start: _start, end: _end };
  35. }