eachYearOfInterval.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import { normalizeInterval } from "./_lib/normalizeInterval.js";
  2. import { constructFrom } from "./constructFrom.js";
  3. /**
  4. * The {@link eachYearOfInterval} function options.
  5. */
  6. /**
  7. * The {@link eachYearOfInterval} function result type. It resolves the proper data type.
  8. * It uses the first argument date object type, starting from the date argument,
  9. * then the start interval date, and finally the end interval date. If
  10. * a context function is passed, it uses the context function return type.
  11. */
  12. /**
  13. * @name eachYearOfInterval
  14. * @category Interval Helpers
  15. * @summary Return the array of yearly timestamps within the specified time interval.
  16. *
  17. * @description
  18. * Return the array of yearly timestamps within the specified time interval.
  19. *
  20. * @typeParam IntervalType - Interval type.
  21. * @typeParam Options - Options type.
  22. *
  23. * @param interval - The interval.
  24. * @param options - An object with options.
  25. *
  26. * @returns The array with starts of yearly timestamps from the month of the interval start to the month of the interval end
  27. *
  28. * @example
  29. * // Each year between 6 February 2014 and 10 August 2017:
  30. * const result = eachYearOfInterval({
  31. * start: new Date(2014, 1, 6),
  32. * end: new Date(2017, 7, 10)
  33. * })
  34. * //=> [
  35. * // Wed Jan 01 2014 00:00:00,
  36. * // Thu Jan 01 2015 00:00:00,
  37. * // Fri Jan 01 2016 00:00:00,
  38. * // Sun Jan 01 2017 00:00:00
  39. * // ]
  40. */
  41. export function eachYearOfInterval(interval, options) {
  42. const { start, end } = normalizeInterval(options?.in, interval);
  43. let reversed = +start > +end;
  44. const endTime = reversed ? +start : +end;
  45. const date = reversed ? end : start;
  46. date.setHours(0, 0, 0, 0);
  47. date.setMonth(0, 1);
  48. let step = options?.step ?? 1;
  49. if (!step) return [];
  50. if (step < 0) {
  51. step = -step;
  52. reversed = !reversed;
  53. }
  54. const dates = [];
  55. while (+date <= endTime) {
  56. dates.push(constructFrom(start, date));
  57. date.setFullYear(date.getFullYear() + step);
  58. }
  59. return reversed ? dates.reverse() : dates;
  60. }
  61. // Fallback for modularized imports:
  62. export default eachYearOfInterval;