index.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import toDate from "../toDate/index.js";
  2. import requiredArgs from "../_lib/requiredArgs/index.js";
  3. /**
  4. * @name eachDayOfInterval
  5. * @category Interval Helpers
  6. * @summary Return the array of dates within the specified time interval.
  7. *
  8. * @description
  9. * Return the array of dates within the specified time interval.
  10. *
  11. * @param {Interval} interval - the interval. See [Interval]{@link https://date-fns.org/docs/Interval}
  12. * @param {Object} [options] - an object with options.
  13. * @param {Number} [options.step=1] - the step to increment by. The value should be more than 1.
  14. * @returns {Date[]} the array with starts of days from the day of the interval start to the day of the interval end
  15. * @throws {TypeError} 1 argument required
  16. * @throws {RangeError} `options.step` must be a number greater than 1
  17. * @throws {RangeError} The start of an interval cannot be after its end
  18. * @throws {RangeError} Date in interval cannot be `Invalid Date`
  19. *
  20. * @example
  21. * // Each day between 6 October 2014 and 10 October 2014:
  22. * const result = eachDayOfInterval({
  23. * start: new Date(2014, 9, 6),
  24. * end: new Date(2014, 9, 10)
  25. * })
  26. * //=> [
  27. * // Mon Oct 06 2014 00:00:00,
  28. * // Tue Oct 07 2014 00:00:00,
  29. * // Wed Oct 08 2014 00:00:00,
  30. * // Thu Oct 09 2014 00:00:00,
  31. * // Fri Oct 10 2014 00:00:00
  32. * // ]
  33. */
  34. export default function eachDayOfInterval(dirtyInterval, options) {
  35. var _options$step;
  36. requiredArgs(1, arguments);
  37. var interval = dirtyInterval || {};
  38. var startDate = toDate(interval.start);
  39. var endDate = toDate(interval.end);
  40. var endTime = endDate.getTime();
  41. // Throw an exception if start date is after end date or if any date is `Invalid Date`
  42. if (!(startDate.getTime() <= endTime)) {
  43. throw new RangeError('Invalid interval');
  44. }
  45. var dates = [];
  46. var currentDate = startDate;
  47. currentDate.setHours(0, 0, 0, 0);
  48. var step = Number((_options$step = options === null || options === void 0 ? void 0 : options.step) !== null && _options$step !== void 0 ? _options$step : 1);
  49. if (step < 1 || isNaN(step)) throw new RangeError('`options.step` must be a number greater than 1');
  50. while (currentDate.getTime() <= endTime) {
  51. dates.push(toDate(currentDate));
  52. currentDate.setDate(currentDate.getDate() + step);
  53. currentDate.setHours(0, 0, 0, 0);
  54. }
  55. return dates;
  56. }