eachWeekOfInterval.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. "use strict";
  2. exports.eachWeekOfInterval = eachWeekOfInterval;
  3. var _index = require("./addWeeks.js");
  4. var _index2 = require("./startOfWeek.js");
  5. var _index3 = require("./toDate.js");
  6. /**
  7. * The {@link eachWeekOfInterval} function options.
  8. */
  9. /**
  10. * @name eachWeekOfInterval
  11. * @category Interval Helpers
  12. * @summary Return the array of weeks within the specified time interval.
  13. *
  14. * @description
  15. * Return the array of weeks within the specified time interval.
  16. *
  17. * @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).
  18. *
  19. * @param interval - The interval.
  20. * @param options - An object with options.
  21. *
  22. * @returns The array with starts of weeks from the week of the interval start to the week of the interval end
  23. *
  24. * @example
  25. * // Each week within interval 6 October 2014 - 23 November 2014:
  26. * const result = eachWeekOfInterval({
  27. * start: new Date(2014, 9, 6),
  28. * end: new Date(2014, 10, 23)
  29. * })
  30. * //=> [
  31. * // Sun Oct 05 2014 00:00:00,
  32. * // Sun Oct 12 2014 00:00:00,
  33. * // Sun Oct 19 2014 00:00:00,
  34. * // Sun Oct 26 2014 00:00:00,
  35. * // Sun Nov 02 2014 00:00:00,
  36. * // Sun Nov 09 2014 00:00:00,
  37. * // Sun Nov 16 2014 00:00:00,
  38. * // Sun Nov 23 2014 00:00:00
  39. * // ]
  40. */
  41. function eachWeekOfInterval(interval, options) {
  42. const startDate = (0, _index3.toDate)(interval.start);
  43. const endDate = (0, _index3.toDate)(interval.end);
  44. let reversed = +startDate > +endDate;
  45. const startDateWeek = reversed
  46. ? (0, _index2.startOfWeek)(endDate, options)
  47. : (0, _index2.startOfWeek)(startDate, options);
  48. const endDateWeek = reversed
  49. ? (0, _index2.startOfWeek)(startDate, options)
  50. : (0, _index2.startOfWeek)(endDate, options);
  51. // Some timezones switch DST at midnight, making start of day unreliable in these timezones, 3pm is a safe bet
  52. startDateWeek.setHours(15);
  53. endDateWeek.setHours(15);
  54. const endTime = +endDateWeek.getTime();
  55. let currentDate = startDateWeek;
  56. let step = options?.step ?? 1;
  57. if (!step) return [];
  58. if (step < 0) {
  59. step = -step;
  60. reversed = !reversed;
  61. }
  62. const dates = [];
  63. while (+currentDate <= endTime) {
  64. currentDate.setHours(0);
  65. dates.push((0, _index3.toDate)(currentDate));
  66. currentDate = (0, _index.addWeeks)(currentDate, step);
  67. currentDate.setHours(15);
  68. }
  69. return reversed ? dates.reverse() : dates;
  70. }