eachYearOfInterval.mjs 1.8 KB

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