1 | import { addWeeks } from "./addWeeks.mjs";
|
2 | import { startOfWeek } from "./startOfWeek.mjs";
|
3 | import { toDate } from "./toDate.mjs";
|
4 |
|
5 | /**
|
6 | * The {@link eachWeekOfInterval} function options.
|
7 | */
|
8 |
|
9 | /**
|
10 | * @name eachWeekOfInterval
|
11 | * @category Interval Helpers
|
12 | * @summary Return the array of weeks within the specified time interval.
|
13 | *
|
14 | * @description
|
15 | * Return the array of weeks 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 | * @param options - An object with options.
|
21 | *
|
22 | * @returns The array with starts of weeks from the week of the interval start to the week of the interval end
|
23 | *
|
24 | * @example
|
25 | * // Each week within interval 6 October 2014 - 23 November 2014:
|
26 | * const result = eachWeekOfInterval({
|
27 | * start: new Date(2014, 9, 6),
|
28 | * end: new Date(2014, 10, 23)
|
29 | * })
|
30 | * //=> [
|
31 | * // Sun Oct 05 2014 00:00:00,
|
32 | * // Sun Oct 12 2014 00:00:00,
|
33 | * // Sun Oct 19 2014 00:00:00,
|
34 | * // Sun Oct 26 2014 00:00:00,
|
35 | * // Sun Nov 02 2014 00:00:00,
|
36 | * // Sun Nov 09 2014 00:00:00,
|
37 | * // Sun Nov 16 2014 00:00:00,
|
38 | * // Sun Nov 23 2014 00:00:00
|
39 | * // ]
|
40 | */
|
41 | export function eachWeekOfInterval(interval, options) {
|
42 | const startDate = toDate(interval.start);
|
43 | const endDate = toDate(interval.end);
|
44 |
|
45 | let reversed = +startDate > +endDate;
|
46 | const startDateWeek = reversed
|
47 | ? startOfWeek(endDate, options)
|
48 | : startOfWeek(startDate, options);
|
49 | const endDateWeek = reversed
|
50 | ? startOfWeek(startDate, options)
|
51 | : startOfWeek(endDate, options);
|
52 |
|
53 | // Some timezones switch DST at midnight, making start of day unreliable in these timezones, 3pm is a safe bet
|
54 | startDateWeek.setHours(15);
|
55 | endDateWeek.setHours(15);
|
56 |
|
57 | const endTime = +endDateWeek.getTime();
|
58 | let currentDate = startDateWeek;
|
59 |
|
60 | let step = options?.step ?? 1;
|
61 | if (!step) return [];
|
62 | if (step < 0) {
|
63 | step = -step;
|
64 | reversed = !reversed;
|
65 | }
|
66 |
|
67 | const dates = [];
|
68 |
|
69 | while (+currentDate <= endTime) {
|
70 | currentDate.setHours(0);
|
71 | dates.push(toDate(currentDate));
|
72 | currentDate = addWeeks(currentDate, step);
|
73 | currentDate.setHours(15);
|
74 | }
|
75 |
|
76 | return reversed ? dates.reverse() : dates;
|
77 | }
|
78 |
|
79 | // Fallback for modularized imports:
|
80 | export default eachWeekOfInterval;
|