1 | ;
|
2 | exports.eachHourOfInterval = eachHourOfInterval;
|
3 | var _index = require("./addHours.js");
|
4 | var _index2 = require("./toDate.js");
|
5 |
|
6 | /**
|
7 | * The {@link eachHourOfInterval} function options.
|
8 | */
|
9 |
|
10 | /**
|
11 | * @name eachHourOfInterval
|
12 | * @category Interval Helpers
|
13 | * @summary Return the array of hours within the specified time interval.
|
14 | *
|
15 | * @description
|
16 | * Return the array of hours within the specified time interval.
|
17 | *
|
18 | * @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).
|
19 | *
|
20 | * @param interval - The interval.
|
21 | * @param options - An object with options.
|
22 | *
|
23 | * @returns The array with starts of hours from the hour of the interval start to the hour of the interval end
|
24 | *
|
25 | * @example
|
26 | * // Each hour between 6 October 2014, 12:00 and 6 October 2014, 15:00
|
27 | * const result = eachHourOfInterval({
|
28 | * start: new Date(2014, 9, 6, 12),
|
29 | * end: new Date(2014, 9, 6, 15)
|
30 | * })
|
31 | * //=> [
|
32 | * // Mon Oct 06 2014 12:00:00,
|
33 | * // Mon Oct 06 2014 13:00:00,
|
34 | * // Mon Oct 06 2014 14:00:00,
|
35 | * // Mon Oct 06 2014 15:00:00
|
36 | * // ]
|
37 | */
|
38 | function eachHourOfInterval(interval, options) {
|
39 | const startDate = (0, _index2.toDate)(interval.start);
|
40 | const endDate = (0, _index2.toDate)(interval.end);
|
41 |
|
42 | let reversed = +startDate > +endDate;
|
43 | const endTime = reversed ? +startDate : +endDate;
|
44 | let currentDate = reversed ? endDate : startDate;
|
45 | currentDate.setMinutes(0, 0, 0);
|
46 |
|
47 | let step = options?.step ?? 1;
|
48 | if (!step) return [];
|
49 | if (step < 0) {
|
50 | step = -step;
|
51 | reversed = !reversed;
|
52 | }
|
53 |
|
54 | const dates = [];
|
55 |
|
56 | while (+currentDate <= endTime) {
|
57 | dates.push((0, _index2.toDate)(currentDate));
|
58 | currentDate = (0, _index.addHours)(currentDate, step);
|
59 | }
|
60 |
|
61 | return reversed ? dates.reverse() : dates;
|
62 | }
|