UNPKG

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