index.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import addMinutes from "../addMinutes/index.js";
  2. import toDate from "../toDate/index.js";
  3. import startOfMinute from "../startOfMinute/index.js";
  4. import requiredArgs from "../_lib/requiredArgs/index.js";
  5. /**
  6. * @name eachMinuteOfInterval
  7. * @category Interval Helpers
  8. * @summary Return the array of minutes within the specified time interval.
  9. *
  10. * @description
  11. * Returns the array of minutes within the specified time interval.
  12. *
  13. * @param {Interval} interval - the interval. See [Interval]{@link https://date-fns.org/docs/Interval}
  14. * @param {Object} [options] - an object with options.
  15. * @param {Number} [options.step=1] - the step to increment by. The step must be equal to or greater than 1
  16. * @throws {TypeError} 1 argument required
  17. * @returns {Date[]} the array with starts of minutes from the minute of the interval start to the minute of the interval end
  18. * @throws {RangeError} `options.step` must be a number equal to or greater than 1
  19. * @throws {RangeError} The start of an interval cannot be after its end
  20. * @throws {RangeError} Date in interval cannot be `Invalid Date`
  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 default function eachMinuteOfInterval(interval, options) {
  36. var _options$step;
  37. requiredArgs(1, arguments);
  38. var startDate = startOfMinute(toDate(interval.start));
  39. var endDate = toDate(interval.end);
  40. var startTime = startDate.getTime();
  41. var endTime = endDate.getTime();
  42. if (startTime >= endTime) {
  43. throw new RangeError('Invalid interval');
  44. }
  45. var dates = [];
  46. var currentDate = startDate;
  47. var step = Number((_options$step = options === null || options === void 0 ? void 0 : options.step) !== null && _options$step !== void 0 ? _options$step : 1);
  48. if (step < 1 || isNaN(step)) throw new RangeError('`options.step` must be a number equal to or greater than 1');
  49. while (currentDate.getTime() <= endTime) {
  50. dates.push(toDate(currentDate));
  51. currentDate = addMinutes(currentDate, step);
  52. }
  53. return dates;
  54. }