eachYearOfInterval.cjs 2.0 KB

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