eachWeekOfInterval.cjs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. "use strict";
  2. exports.eachWeekOfInterval = eachWeekOfInterval;
  3. var _index = require("./_lib/normalizeInterval.cjs");
  4. var _index2 = require("./addWeeks.cjs");
  5. var _index3 = require("./constructFrom.cjs");
  6. var _index4 = require("./startOfWeek.cjs");
  7. /**
  8. * The {@link eachWeekOfInterval} function options.
  9. */
  10. /**
  11. * The {@link eachWeekOfInterval} function result type. It resolves the proper data type.
  12. * It uses the first argument date object type, starting from the interval start date,
  13. * then the end interval date. If a context function is passed, it uses the context function return type.
  14. */
  15. /**
  16. * @name eachWeekOfInterval
  17. * @category Interval Helpers
  18. * @summary Return the array of weeks within the specified time interval.
  19. *
  20. * @description
  21. * Return the array of weeks within the specified time interval.
  22. *
  23. * @param interval - The interval.
  24. * @param options - An object with options.
  25. *
  26. * @returns The array with starts of weeks from the week of the interval start to the week of the interval end
  27. *
  28. * @example
  29. * // Each week within interval 6 October 2014 - 23 November 2014:
  30. * const result = eachWeekOfInterval({
  31. * start: new Date(2014, 9, 6),
  32. * end: new Date(2014, 10, 23)
  33. * })
  34. * //=> [
  35. * // Sun Oct 05 2014 00:00:00,
  36. * // Sun Oct 12 2014 00:00:00,
  37. * // Sun Oct 19 2014 00:00:00,
  38. * // Sun Oct 26 2014 00:00:00,
  39. * // Sun Nov 02 2014 00:00:00,
  40. * // Sun Nov 09 2014 00:00:00,
  41. * // Sun Nov 16 2014 00:00:00,
  42. * // Sun Nov 23 2014 00:00:00
  43. * // ]
  44. */
  45. function eachWeekOfInterval(interval, options) {
  46. const { start, end } = (0, _index.normalizeInterval)(options?.in, interval);
  47. let reversed = +start > +end;
  48. const startDateWeek = reversed
  49. ? (0, _index4.startOfWeek)(end, options)
  50. : (0, _index4.startOfWeek)(start, options);
  51. const endDateWeek = reversed
  52. ? (0, _index4.startOfWeek)(start, options)
  53. : (0, _index4.startOfWeek)(end, options);
  54. startDateWeek.setHours(15);
  55. endDateWeek.setHours(15);
  56. const endTime = +endDateWeek.getTime();
  57. let currentDate = startDateWeek;
  58. let step = options?.step ?? 1;
  59. if (!step) return [];
  60. if (step < 0) {
  61. step = -step;
  62. reversed = !reversed;
  63. }
  64. const dates = [];
  65. while (+currentDate <= endTime) {
  66. currentDate.setHours(0);
  67. dates.push((0, _index3.constructFrom)(start, currentDate));
  68. currentDate = (0, _index2.addWeeks)(currentDate, step);
  69. currentDate.setHours(15);
  70. }
  71. return reversed ? dates.reverse() : dates;
  72. }