interval.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import { normalizeDates } from "./_lib/normalizeDates.js";
  2. /**
  3. * The {@link interval} function options.
  4. */
  5. /**
  6. * The {@link interval} function result type. It resolves the proper data type.
  7. * It uses the first argument date object type, starting from the start argument,
  8. * then the end interval date. If a context function is passed, it uses the context
  9. * function return type.
  10. */
  11. /**
  12. * @name interval
  13. * @category Interval Helpers
  14. * @summary Creates an interval object and validates its values.
  15. *
  16. * @description
  17. * Creates a normalized interval object and validates its values. If the interval is invalid, an exception is thrown.
  18. *
  19. * @typeParam StartDate - Start date type.
  20. * @typeParam EndDate - End date type.
  21. * @typeParam Options - Options type.
  22. *
  23. * @param start - The start of the interval.
  24. * @param end - The end of the interval.
  25. * @param options - The options object.
  26. *
  27. * @throws `Start date is invalid` when `start` is invalid.
  28. * @throws `End date is invalid` when `end` is invalid.
  29. * @throws `End date must be after start date` when end is before `start` and `options.assertPositive` is true.
  30. *
  31. * @returns The normalized and validated interval object.
  32. */
  33. export function interval(start, end, options) {
  34. const [_start, _end] = normalizeDates(options?.in, start, end);
  35. if (isNaN(+_start)) throw new TypeError("Start date is invalid");
  36. if (isNaN(+_end)) throw new TypeError("End date is invalid");
  37. if (options?.assertPositive && +_start > +_end)
  38. throw new TypeError("End date must be after start date");
  39. return { start: _start, end: _end };
  40. }
  41. // Fallback for modularized imports:
  42. export default interval;