eachMonthOfInterval.cjs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. "use strict";
  2. exports.eachMonthOfInterval = eachMonthOfInterval;
  3. var _index = require("./_lib/normalizeInterval.cjs");
  4. var _index2 = require("./constructFrom.cjs");
  5. /**
  6. * The {@link eachMonthOfInterval} function options.
  7. */
  8. /**
  9. * The {@link eachMonthOfInterval} function result type. It resolves the proper data type.
  10. */
  11. /**
  12. * @name eachMonthOfInterval
  13. * @category Interval Helpers
  14. * @summary Return the array of months within the specified time interval.
  15. *
  16. * @description
  17. * Return the array of months within the specified time interval.
  18. *
  19. * @typeParam IntervalType - Interval type.
  20. * @typeParam Options - Options type.
  21. *
  22. * @param interval - The interval.
  23. * @param options - An object with options.
  24. *
  25. * @returns The array with starts of months from the month of the interval start to the month of the interval end
  26. *
  27. * @example
  28. * // Each month between 6 February 2014 and 10 August 2014:
  29. * const result = eachMonthOfInterval({
  30. * start: new Date(2014, 1, 6),
  31. * end: new Date(2014, 7, 10)
  32. * })
  33. * //=> [
  34. * // Sat Feb 01 2014 00:00:00,
  35. * // Sat Mar 01 2014 00:00:00,
  36. * // Tue Apr 01 2014 00:00:00,
  37. * // Thu May 01 2014 00:00:00,
  38. * // Sun Jun 01 2014 00:00:00,
  39. * // Tue Jul 01 2014 00:00:00,
  40. * // Fri Aug 01 2014 00:00:00
  41. * // ]
  42. */
  43. function eachMonthOfInterval(interval, options) {
  44. const { start, end } = (0, _index.normalizeInterval)(options?.in, interval);
  45. let reversed = +start > +end;
  46. const endTime = reversed ? +start : +end;
  47. const date = reversed ? end : start;
  48. date.setHours(0, 0, 0, 0);
  49. date.setDate(1);
  50. let step = options?.step ?? 1;
  51. if (!step) return [];
  52. if (step < 0) {
  53. step = -step;
  54. reversed = !reversed;
  55. }
  56. const dates = [];
  57. while (+date <= endTime) {
  58. dates.push((0, _index2.constructFrom)(start, date));
  59. date.setMonth(date.getMonth() + step);
  60. }
  61. return reversed ? dates.reverse() : dates;
  62. }