eachMonthOfInterval.js 1.9 KB

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