eachHourOfInterval.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. "use strict";
  2. exports.eachHourOfInterval = eachHourOfInterval;
  3. var _index = require("./addHours.js");
  4. var _index2 = require("./toDate.js");
  5. /**
  6. * The {@link eachHourOfInterval} function options.
  7. */
  8. /**
  9. * @name eachHourOfInterval
  10. * @category Interval Helpers
  11. * @summary Return the array of hours within the specified time interval.
  12. *
  13. * @description
  14. * Return the array of hours within the specified time interval.
  15. *
  16. * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
  17. *
  18. * @param interval - The interval.
  19. * @param options - An object with options.
  20. *
  21. * @returns The array with starts of hours from the hour of the interval start to the hour of the interval end
  22. *
  23. * @example
  24. * // Each hour between 6 October 2014, 12:00 and 6 October 2014, 15:00
  25. * const result = eachHourOfInterval({
  26. * start: new Date(2014, 9, 6, 12),
  27. * end: new Date(2014, 9, 6, 15)
  28. * })
  29. * //=> [
  30. * // Mon Oct 06 2014 12:00:00,
  31. * // Mon Oct 06 2014 13:00:00,
  32. * // Mon Oct 06 2014 14:00:00,
  33. * // Mon Oct 06 2014 15:00:00
  34. * // ]
  35. */
  36. function eachHourOfInterval(interval, options) {
  37. const startDate = (0, _index2.toDate)(interval.start);
  38. const endDate = (0, _index2.toDate)(interval.end);
  39. let reversed = +startDate > +endDate;
  40. const endTime = reversed ? +startDate : +endDate;
  41. let currentDate = reversed ? endDate : startDate;
  42. currentDate.setMinutes(0, 0, 0);
  43. let step = options?.step ?? 1;
  44. if (!step) return [];
  45. if (step < 0) {
  46. step = -step;
  47. reversed = !reversed;
  48. }
  49. const dates = [];
  50. while (+currentDate <= endTime) {
  51. dates.push((0, _index2.toDate)(currentDate));
  52. currentDate = (0, _index.addHours)(currentDate, step);
  53. }
  54. return reversed ? dates.reverse() : dates;
  55. }