index.js 2.3 KB

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