eachMinuteOfInterval.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import { normalizeInterval } from "./_lib/normalizeInterval.js";
  2. import { addMinutes } from "./addMinutes.js";
  3. import { constructFrom } from "./constructFrom.js";
  4. /**
  5. * The {@link eachMinuteOfInterval} function options.
  6. */
  7. /**
  8. * The {@link eachMinuteOfInterval} function result type. It resolves the proper data type.
  9. * It uses the first argument date object type, starting from the date argument,
  10. * then the start interval date, and finally the end interval date. If
  11. * a context function is passed, it uses the context function return type.
  12. */
  13. /**
  14. * @name eachMinuteOfInterval
  15. * @category Interval Helpers
  16. * @summary Return the array of minutes within the specified time interval.
  17. *
  18. * @description
  19. * Returns the array of minutes within the specified time interval.
  20. *
  21. * @typeParam IntervalType - Interval type.
  22. * @typeParam Options - Options type.
  23. *
  24. * @param interval - The interval.
  25. * @param options - An object with options.
  26. *
  27. * @returns The array with starts of minutes from the minute of the interval start to the minute of the interval end
  28. *
  29. * @example
  30. * // Each minute between 14 October 2020, 13:00 and 14 October 2020, 13:03
  31. * const result = eachMinuteOfInterval({
  32. * start: new Date(2014, 9, 14, 13),
  33. * end: new Date(2014, 9, 14, 13, 3)
  34. * })
  35. * //=> [
  36. * // Wed Oct 14 2014 13:00:00,
  37. * // Wed Oct 14 2014 13:01:00,
  38. * // Wed Oct 14 2014 13:02:00,
  39. * // Wed Oct 14 2014 13:03:00
  40. * // ]
  41. */
  42. export function eachMinuteOfInterval(interval, options) {
  43. const { start, end } = normalizeInterval(options?.in, interval);
  44. // Set to the start of the minute
  45. start.setSeconds(0, 0);
  46. let reversed = +start > +end;
  47. const endTime = reversed ? +start : +end;
  48. let date = reversed ? end : start;
  49. let step = options?.step ?? 1;
  50. if (!step) return [];
  51. if (step < 0) {
  52. step = -step;
  53. reversed = !reversed;
  54. }
  55. const dates = [];
  56. while (+date <= endTime) {
  57. dates.push(constructFrom(start, date));
  58. date = addMinutes(date, step);
  59. }
  60. return reversed ? dates.reverse() : dates;
  61. }
  62. // Fallback for modularized imports:
  63. export default eachMinuteOfInterval;