index.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. * var 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. requiredArgs(1, arguments);
  36. var interval = dirtyInterval || {};
  37. var startDate = toDate(interval.start);
  38. var endDate = toDate(interval.end);
  39. var startTime = startDate.getTime();
  40. var endTime = endDate.getTime(); // Throw an exception if start date is after end date or if any date is `Invalid Date`
  41. if (!(startTime <= endTime)) {
  42. throw new RangeError('Invalid interval');
  43. }
  44. var dates = [];
  45. var currentDate = startDate;
  46. currentDate.setMinutes(0, 0, 0);
  47. var step = options && 'step' in options ? Number(options.step) : 1;
  48. if (step < 1 || isNaN(step)) throw new RangeError('`options.step` must be a number greater than 1');
  49. while (currentDate.getTime() <= endTime) {
  50. dates.push(toDate(currentDate));
  51. currentDate = addHours(currentDate, step);
  52. }
  53. return dates;
  54. }