eachHourOfInterval.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import { normalizeInterval } from "./_lib/normalizeInterval.js";
  2. import { constructFrom } from "./constructFrom.js";
  3. /**
  4. * The {@link eachHourOfInterval} function options.
  5. */
  6. /**
  7. * The {@link eachHourOfInterval} function result type.
  8. * Resolves to the appropriate date type based on inputs.
  9. */
  10. /**
  11. * @name eachHourOfInterval
  12. * @category Interval Helpers
  13. * @summary Return the array of hours within the specified time interval.
  14. *
  15. * @description
  16. * Return the array of hours within the specified time interval.
  17. *
  18. * @typeParam IntervalType - Interval type.
  19. * @typeParam Options - Options type.
  20. *
  21. * @param interval - The interval.
  22. * @param options - An object with options.
  23. *
  24. * @returns The array with starts of hours from the hour of the interval start to the hour of the interval end
  25. *
  26. * @example
  27. * // Each hour between 6 October 2014, 12:00 and 6 October 2014, 15:00
  28. * const result = eachHourOfInterval({
  29. * start: new Date(2014, 9, 6, 12),
  30. * end: new Date(2014, 9, 6, 15)
  31. * });
  32. * //=> [
  33. * // Mon Oct 06 2014 12:00:00,
  34. * // Mon Oct 06 2014 13:00:00,
  35. * // Mon Oct 06 2014 14:00:00,
  36. * // Mon Oct 06 2014 15:00:00
  37. * // ]
  38. */
  39. export function eachHourOfInterval(interval, options) {
  40. const { start, end } = normalizeInterval(options?.in, interval);
  41. let reversed = +start > +end;
  42. const endTime = reversed ? +start : +end;
  43. const date = reversed ? end : start;
  44. date.setMinutes(0, 0, 0);
  45. let step = options?.step ?? 1;
  46. if (!step) return [];
  47. if (step < 0) {
  48. step = -step;
  49. reversed = !reversed;
  50. }
  51. const dates = [];
  52. while (+date <= endTime) {
  53. dates.push(constructFrom(start, date));
  54. date.setHours(date.getHours() + step);
  55. }
  56. return reversed ? dates.reverse() : dates;
  57. }
  58. // Fallback for modularized imports:
  59. export default eachHourOfInterval;