UNPKG

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