eachMinuteOfInterval.js 1.9 KB

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