index.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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 starts of minutes from the hour of the interval start to the hour of the interval end
  16. * @throws {TypeError} 1 argument requie value should be more than 1.
  17. * @returns {Date[]} the array withred
  18. * @throws {RangeError} `options.step` must be a number equal 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. requiredArgs(1, arguments);
  37. var startDate = startOfMinute(toDate(interval.start));
  38. var endDate = startOfMinute(toDate(interval.end));
  39. var startTime = startDate.getTime();
  40. var endTime = endDate.getTime();
  41. if (startTime >= endTime) {
  42. throw new RangeError('Invalid interval');
  43. }
  44. var dates = [];
  45. var currentDate = startDate;
  46. var step = options && 'step' in options ? Number(options.step) : 1;
  47. if (step < 1 || isNaN(step)) throw new RangeError('`options.step` must be a number equal or greater than 1');
  48. while (currentDate.getTime() <= endTime) {
  49. dates.push(toDate(currentDate));
  50. currentDate = addMinutes(currentDate, step);
  51. }
  52. return dates;
  53. }