eachYearOfInterval.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. "use strict";
  2. exports.eachYearOfInterval = eachYearOfInterval;
  3. var _index = require("./toDate.js");
  4. /**
  5. * The {@link eachYearOfInterval} function options.
  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. */
  34. function eachYearOfInterval(interval, options) {
  35. const startDate = (0, _index.toDate)(interval.start);
  36. const endDate = (0, _index.toDate)(interval.end);
  37. let reversed = +startDate > +endDate;
  38. const endTime = reversed ? +startDate : +endDate;
  39. const currentDate = reversed ? endDate : startDate;
  40. currentDate.setHours(0, 0, 0, 0);
  41. currentDate.setMonth(0, 1);
  42. let step = options?.step ?? 1;
  43. if (!step) return [];
  44. if (step < 0) {
  45. step = -step;
  46. reversed = !reversed;
  47. }
  48. const dates = [];
  49. while (+currentDate <= endTime) {
  50. dates.push((0, _index.toDate)(currentDate));
  51. currentDate.setFullYear(currentDate.getFullYear() + step);
  52. }
  53. return reversed ? dates.reverse() : dates;
  54. }