eachWeekOfInterval.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import { normalizeInterval } from "./_lib/normalizeInterval.js";
  2. import { addWeeks } from "./addWeeks.js";
  3. import { constructFrom } from "./constructFrom.js";
  4. import { startOfWeek } from "./startOfWeek.js";
  5. /**
  6. * The {@link eachWeekOfInterval} function options.
  7. */
  8. /**
  9. * The {@link eachWeekOfInterval} function result type. It resolves the proper data type.
  10. * It uses the first argument date object type, starting from the interval start date,
  11. * then the end interval date. If a context function is passed, it uses the context function return type.
  12. */
  13. /**
  14. * @name eachWeekOfInterval
  15. * @category Interval Helpers
  16. * @summary Return the array of weeks within the specified time interval.
  17. *
  18. * @description
  19. * Return the array of weeks within the specified time interval.
  20. *
  21. * @param interval - The interval.
  22. * @param options - An object with options.
  23. *
  24. * @returns The array with starts of weeks from the week of the interval start to the week of the interval end
  25. *
  26. * @example
  27. * // Each week within interval 6 October 2014 - 23 November 2014:
  28. * const result = eachWeekOfInterval({
  29. * start: new Date(2014, 9, 6),
  30. * end: new Date(2014, 10, 23)
  31. * })
  32. * //=> [
  33. * // Sun Oct 05 2014 00:00:00,
  34. * // Sun Oct 12 2014 00:00:00,
  35. * // Sun Oct 19 2014 00:00:00,
  36. * // Sun Oct 26 2014 00:00:00,
  37. * // Sun Nov 02 2014 00:00:00,
  38. * // Sun Nov 09 2014 00:00:00,
  39. * // Sun Nov 16 2014 00:00:00,
  40. * // Sun Nov 23 2014 00:00:00
  41. * // ]
  42. */
  43. export function eachWeekOfInterval(interval, options) {
  44. const { start, end } = normalizeInterval(options?.in, interval);
  45. let reversed = +start > +end;
  46. const startDateWeek = reversed
  47. ? startOfWeek(end, options)
  48. : startOfWeek(start, options);
  49. const endDateWeek = reversed
  50. ? startOfWeek(start, options)
  51. : startOfWeek(end, options);
  52. startDateWeek.setHours(15);
  53. endDateWeek.setHours(15);
  54. const endTime = +endDateWeek.getTime();
  55. let currentDate = startDateWeek;
  56. let step = options?.step ?? 1;
  57. if (!step) return [];
  58. if (step < 0) {
  59. step = -step;
  60. reversed = !reversed;
  61. }
  62. const dates = [];
  63. while (+currentDate <= endTime) {
  64. currentDate.setHours(0);
  65. dates.push(constructFrom(start, currentDate));
  66. currentDate = addWeeks(currentDate, step);
  67. currentDate.setHours(15);
  68. }
  69. return reversed ? dates.reverse() : dates;
  70. }
  71. // Fallback for modularized imports:
  72. export default eachWeekOfInterval;