eachMinuteOfInterval.mjs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import { addMinutes } from "./addMinutes.mjs";
  2. import { startOfMinute } from "./startOfMinute.mjs";
  3. import { toDate } from "./toDate.mjs";
  4. /**
  5. * The {@link eachMinuteOfInterval} function options.
  6. */
  7. /**
  8. * @name eachMinuteOfInterval
  9. * @category Interval Helpers
  10. * @summary Return the array of minutes within the specified time interval.
  11. *
  12. * @description
  13. * Returns the array of minutes within the specified time interval.
  14. *
  15. * @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).
  16. *
  17. * @param interval - The interval.
  18. * @param options - An object with options.
  19. *
  20. * @returns The array with starts of minutes from the minute of the interval start to the minute of the interval end
  21. *
  22. * @example
  23. * // Each minute between 14 October 2020, 13:00 and 14 October 2020, 13:03
  24. * const result = eachMinuteOfInterval({
  25. * start: new Date(2014, 9, 14, 13),
  26. * end: new Date(2014, 9, 14, 13, 3)
  27. * })
  28. * //=> [
  29. * // Wed Oct 14 2014 13:00:00,
  30. * // Wed Oct 14 2014 13:01:00,
  31. * // Wed Oct 14 2014 13:02:00,
  32. * // Wed Oct 14 2014 13:03:00
  33. * // ]
  34. */
  35. export function eachMinuteOfInterval(interval, options) {
  36. const startDate = startOfMinute(toDate(interval.start));
  37. const endDate = toDate(interval.end);
  38. let reversed = +startDate > +endDate;
  39. const endTime = reversed ? +startDate : +endDate;
  40. let currentDate = reversed ? endDate : startDate;
  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 = addMinutes(currentDate, step);
  51. }
  52. return reversed ? dates.reverse() : dates;
  53. }
  54. // Fallback for modularized imports:
  55. export default eachMinuteOfInterval;