index.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import addQuarters from "../addQuarters/index.js";
  2. import startOfQuarter from "../startOfQuarter/index.js";
  3. import toDate from "../toDate/index.js";
  4. import requiredArgs from "../_lib/requiredArgs/index.js";
  5. /**
  6. * @name eachQuarterOfInterval
  7. * @category Interval Helpers
  8. * @summary Return the array of quarters within the specified time interval.
  9. *
  10. * @description
  11. * Return the array of quarters within the specified time interval.
  12. *
  13. * @param {Interval} interval - the interval. See [Interval]{@link https://date-fns.org/docs/Interval}
  14. * @returns {Date[]} the array with starts of quarters from the quarter of the interval start to the quarter of the interval end
  15. * @throws {TypeError} 1 argument required
  16. * @throws {RangeError} The start of an interval cannot be after its end
  17. * @throws {RangeError} Date in interval cannot be `Invalid Date`
  18. *
  19. * @example
  20. * // Each quarter within interval 6 February 2014 - 10 August 2014:
  21. * const result = eachQuarterOfInterval({
  22. * start: new Date(2014, 1, 6),
  23. * end: new Date(2014, 7, 10)
  24. * })
  25. * //=> [
  26. * // Wed Jan 01 2014 00:00:00,
  27. * // Tue Apr 01 2014 00:00:00,
  28. * // Tue Jul 01 2014 00:00:00,
  29. * // ]
  30. */
  31. export default function eachQuarterOfInterval(dirtyInterval) {
  32. requiredArgs(1, arguments);
  33. var interval = dirtyInterval || {};
  34. var startDate = toDate(interval.start);
  35. var endDate = toDate(interval.end);
  36. var endTime = endDate.getTime();
  37. // Throw an exception if start date is after end date or if any date is `Invalid Date`
  38. if (!(startDate.getTime() <= endTime)) {
  39. throw new RangeError('Invalid interval');
  40. }
  41. var startDateQuarter = startOfQuarter(startDate);
  42. var endDateQuarter = startOfQuarter(endDate);
  43. endTime = endDateQuarter.getTime();
  44. var quarters = [];
  45. var currentQuarter = startDateQuarter;
  46. while (currentQuarter.getTime() <= endTime) {
  47. quarters.push(toDate(currentQuarter));
  48. currentQuarter = addQuarters(currentQuarter, 1);
  49. }
  50. return quarters;
  51. }