eachHourOfInterval.mjs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import { addHours } from "./addHours.mjs";
  2. import { toDate } from "./toDate.mjs";
  3. /**
  4. * The {@link eachHourOfInterval} function options.
  5. */
  6. /**
  7. * @name eachHourOfInterval
  8. * @category Interval Helpers
  9. * @summary Return the array of hours within the specified time interval.
  10. *
  11. * @description
  12. * Return the array of hours within the specified time interval.
  13. *
  14. * @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).
  15. *
  16. * @param interval - The interval.
  17. * @param options - An object with options.
  18. *
  19. * @returns The array with starts of hours from the hour of the interval start to the hour of the interval end
  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 function eachHourOfInterval(interval, options) {
  35. const startDate = toDate(interval.start);
  36. const endDate = toDate(interval.end);
  37. let reversed = +startDate > +endDate;
  38. const endTime = reversed ? +startDate : +endDate;
  39. let currentDate = reversed ? endDate : startDate;
  40. currentDate.setMinutes(0, 0, 0);
  41. let step = options?.step ?? 1;
  42. if (!step) return [];
  43. if (step < 0) {
  44. step = -step;
  45. reversed = !reversed;
  46. }
  47. const dates = [];
  48. while (+currentDate <= endTime) {
  49. dates.push(toDate(currentDate));
  50. currentDate = addHours(currentDate, step);
  51. }
  52. return reversed ? dates.reverse() : dates;
  53. }
  54. // Fallback for modularized imports:
  55. export default eachHourOfInterval;