interval.mjs 1.4 KB

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