eachQuarterOfInterval.js 1.9 KB

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