eachQuarterOfInterval.mjs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import { addQuarters } from "./addQuarters.mjs";
  2. import { startOfQuarter } from "./startOfQuarter.mjs";
  3. import { toDate } from "./toDate.mjs";
  4. /**
  5. * The {@link eachQuarterOfInterval} function options.
  6. */
  7. /**
  8. * @name eachQuarterOfInterval
  9. * @category Interval Helpers
  10. * @summary Return the array of quarters within the specified time interval.
  11. *
  12. * @description
  13. * Return the array of quarters within the specified time interval.
  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 interval - The interval
  18. *
  19. * @returns The array with starts of quarters from the quarter of the interval start to the quarter of the interval end
  20. *
  21. * @example
  22. * // Each quarter within interval 6 February 2014 - 10 August 2014:
  23. * const result = eachQuarterOfInterval({
  24. * start: new Date(2014, 1, 6),
  25. * end: new Date(2014, 7, 10)
  26. * })
  27. * //=> [
  28. * // Wed Jan 01 2014 00:00:00,
  29. * // Tue Apr 01 2014 00:00:00,
  30. * // Tue Jul 01 2014 00:00:00,
  31. * // ]
  32. */
  33. export function eachQuarterOfInterval(interval, options) {
  34. const startDate = toDate(interval.start);
  35. const endDate = toDate(interval.end);
  36. let reversed = +startDate > +endDate;
  37. const endTime = reversed
  38. ? +startOfQuarter(startDate)
  39. : +startOfQuarter(endDate);
  40. let currentDate = reversed
  41. ? startOfQuarter(endDate)
  42. : startOfQuarter(startDate);
  43. let step = options?.step ?? 1;
  44. if (!step) return [];
  45. if (step < 0) {
  46. step = -step;
  47. reversed = !reversed;
  48. }
  49. const dates = [];
  50. while (+currentDate <= endTime) {
  51. dates.push(toDate(currentDate));
  52. currentDate = addQuarters(currentDate, step);
  53. }
  54. return reversed ? dates.reverse() : dates;
  55. }
  56. // Fallback for modularized imports:
  57. export default eachQuarterOfInterval;