UNPKG

1.8 kBJavaScriptView Raw
1import { toDate } from "./toDate.mjs";
2
3/**
4 * The {@link eachYearOfInterval} function options.
5 */
6
7/**
8 * @name eachYearOfInterval
9 * @category Interval Helpers
10 * @summary Return the array of yearly timestamps within the specified time interval.
11 *
12 * @description
13 * Return the array of yearly timestamps within the specified time interval.
14 *
15 * @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).
16 *
17 * @param interval - The interval.
18 *
19 * @returns The array with starts of yearly timestamps from the month of the interval start to the month of the interval end
20 *
21 * @example
22 * // Each year between 6 February 2014 and 10 August 2017:
23 * const result = eachYearOfInterval({
24 * start: new Date(2014, 1, 6),
25 * end: new Date(2017, 7, 10)
26 * })
27 * //=> [
28 * // Wed Jan 01 2014 00:00:00,
29 * // Thu Jan 01 2015 00:00:00,
30 * // Fri Jan 01 2016 00:00:00,
31 * // Sun Jan 01 2017 00:00:00
32 * // ]
33 */
34export function eachYearOfInterval(interval, options) {
35 const startDate = toDate(interval.start);
36 const endDate = toDate(interval.end);
37
38 let reversed = +startDate > +endDate;
39 const endTime = reversed ? +startDate : +endDate;
40 const currentDate = reversed ? endDate : startDate;
41 currentDate.setHours(0, 0, 0, 0);
42 currentDate.setMonth(0, 1);
43
44 let step = options?.step ?? 1;
45 if (!step) return [];
46 if (step < 0) {
47 step = -step;
48 reversed = !reversed;
49 }
50
51 const dates = [];
52
53 while (+currentDate <= endTime) {
54 dates.push(toDate(currentDate));
55 currentDate.setFullYear(currentDate.getFullYear() + step);
56 }
57
58 return reversed ? dates.reverse() : dates;
59}
60
61// Fallback for modularized imports:
62export default eachYearOfInterval;