index.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import eachDayOfInterval from "../eachDayOfInterval/index.js";
  2. import isSunday from "../isSunday/index.js";
  3. import isWeekend from "../isWeekend/index.js";
  4. import requiredArgs from "../_lib/requiredArgs/index.js";
  5. /**
  6. * @name eachWeekendOfInterval
  7. * @category Interval Helpers
  8. * @summary List all the Saturdays and Sundays in the given date interval.
  9. *
  10. * @description
  11. * Get all the Saturdays and Sundays in the given date interval.
  12. *
  13. * @param {Interval} interval - the given interval. See [Interval]{@link https://date-fns.org/docs/Interval}
  14. * @returns {Date[]} an array containing all the Saturdays and Sundays
  15. * @throws {TypeError} 1 argument required
  16. * @throws {RangeError} The start of an interval cannot be after its end
  17. * @throws {RangeError} Date in interval cannot be `Invalid Date`
  18. *
  19. * @example
  20. * // Lists all Saturdays and Sundays in the given date interval
  21. * const result = eachWeekendOfInterval({
  22. * start: new Date(2018, 8, 17),
  23. * end: new Date(2018, 8, 30)
  24. * })
  25. * //=> [
  26. * // Sat Sep 22 2018 00:00:00,
  27. * // Sun Sep 23 2018 00:00:00,
  28. * // Sat Sep 29 2018 00:00:00,
  29. * // Sun Sep 30 2018 00:00:00
  30. * // ]
  31. */
  32. export default function eachWeekendOfInterval(interval) {
  33. requiredArgs(1, arguments);
  34. var dateInterval = eachDayOfInterval(interval);
  35. var weekends = [];
  36. var index = 0;
  37. while (index < dateInterval.length) {
  38. var date = dateInterval[index++];
  39. if (isWeekend(date)) {
  40. weekends.push(date);
  41. if (isSunday(date)) index = index + 5;
  42. }
  43. }
  44. return weekends;
  45. }