eachQuarterOfInterval.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import { normalizeInterval } from "./_lib/normalizeInterval.js";
  2. import { addQuarters } from "./addQuarters.js";
  3. import { constructFrom } from "./constructFrom.js";
  4. import { startOfQuarter } from "./startOfQuarter.js";
  5. /**
  6. * The {@link eachQuarterOfInterval} function options.
  7. */
  8. /**
  9. * The {@link eachQuarterOfInterval} function result type. It resolves the proper data type.
  10. * It uses the first argument date object type, starting from the date argument,
  11. * then the start interval date, and finally the end interval date. If
  12. * a context function is passed, it uses the context function return type.
  13. */
  14. /**
  15. * @name eachQuarterOfInterval
  16. * @category Interval Helpers
  17. * @summary Return the array of quarters within the specified time interval.
  18. *
  19. * @description
  20. * Return the array of quarters within the specified time interval.
  21. *
  22. * @typeParam IntervalType - Interval type.
  23. * @typeParam Options - Options type.
  24. *
  25. * @param interval - The interval
  26. * @param options - An object with options
  27. *
  28. * @returns The array with starts of quarters from the quarter of the interval start to the quarter of the interval end
  29. *
  30. * @example
  31. * // Each quarter within interval 6 February 2014 - 10 August 2014:
  32. * const result = eachQuarterOfInterval({
  33. * start: new Date(2014, 1, 6),
  34. * end: new Date(2014, 7, 10),
  35. * })
  36. * //=> [
  37. * // Wed Jan 01 2014 00:00:00,
  38. * // Tue Apr 01 2014 00:00:00,
  39. * // Tue Jul 01 2014 00:00:00,
  40. * // ]
  41. */
  42. export function eachQuarterOfInterval(interval, options) {
  43. const { start, end } = normalizeInterval(options?.in, interval);
  44. let reversed = +start > +end;
  45. const endTime = reversed ? +startOfQuarter(start) : +startOfQuarter(end);
  46. let date = reversed ? startOfQuarter(end) : startOfQuarter(start);
  47. let step = options?.step ?? 1;
  48. if (!step) return [];
  49. if (step < 0) {
  50. step = -step;
  51. reversed = !reversed;
  52. }
  53. const dates = [];
  54. while (+date <= endTime) {
  55. dates.push(constructFrom(start, date));
  56. date = addQuarters(date, step);
  57. }
  58. return reversed ? dates.reverse() : dates;
  59. }
  60. // Fallback for modularized imports:
  61. export default eachQuarterOfInterval;