eachWeekendOfInterval.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import { normalizeInterval } from "./_lib/normalizeInterval.js";
  2. import { constructFrom } from "./constructFrom.js";
  3. import { eachDayOfInterval } from "./eachDayOfInterval.js";
  4. import { isWeekend } from "./isWeekend.js";
  5. /**
  6. * The {@link eachWeekendOfInterval} function options.
  7. */
  8. /**
  9. * The {@link eachWeekendOfInterval} function result type.
  10. */
  11. /**
  12. * @name eachWeekendOfInterval
  13. * @category Interval Helpers
  14. * @summary List all the Saturdays and Sundays in the given date interval.
  15. *
  16. * @description
  17. * Get all the Saturdays and Sundays in the given date interval.
  18. *
  19. * @typeParam IntervalType - Interval type.
  20. * @typeParam Options - Options type.
  21. *
  22. * @param interval - The given interval
  23. * @param options - An object with options
  24. *
  25. * @returns An array containing all the Saturdays and Sundays
  26. *
  27. * @example
  28. * // Lists all Saturdays and Sundays in the given date interval
  29. * const result = eachWeekendOfInterval({
  30. * start: new Date(2018, 8, 17),
  31. * end: new Date(2018, 8, 30)
  32. * })
  33. * //=> [
  34. * // Sat Sep 22 2018 00:00:00,
  35. * // Sun Sep 23 2018 00:00:00,
  36. * // Sat Sep 29 2018 00:00:00,
  37. * // Sun Sep 30 2018 00:00:00
  38. * // ]
  39. */
  40. export function eachWeekendOfInterval(interval, options) {
  41. const { start, end } = normalizeInterval(options?.in, interval);
  42. const dateInterval = eachDayOfInterval({ start, end }, options);
  43. const weekends = [];
  44. let index = 0;
  45. while (index < dateInterval.length) {
  46. const date = dateInterval[index++];
  47. if (isWeekend(date)) weekends.push(constructFrom(start, date));
  48. }
  49. return weekends;
  50. }
  51. // Fallback for modularized imports:
  52. export default eachWeekendOfInterval;