eachHourOfInterval.cjs 1.8 KB

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