index.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import toDate from "../toDate/index.js";
  2. import requiredArgs from "../_lib/requiredArgs/index.js";
  3. /**
  4. * @name eachYearOfInterval
  5. * @category Interval Helpers
  6. * @summary Return the array of yearly timestamps within the specified time interval.
  7. *
  8. * @description
  9. * Return the array of yearly timestamps within the specified time interval.
  10. *
  11. * @param {Interval} interval - the interval. See [Interval]{@link https://date-fns.org/docs/Interval}
  12. * @returns {Date[]} the array with starts of yearly timestamps from the month of the interval start to the month of the interval end
  13. * @throws {TypeError} 1 argument required
  14. * @throws {RangeError} The start of an interval cannot be after its end
  15. * @throws {RangeError} Date in interval cannot be `Invalid Date`
  16. *
  17. * @example
  18. * // Each year between 6 February 2014 and 10 August 2017:
  19. * var result = eachYearOfInterval({
  20. * start: new Date(2014, 1, 6),
  21. * end: new Date(2017, 7, 10)
  22. * })
  23. * //=> [
  24. * // Wed Jan 01 2014 00:00:00,
  25. * // Thu Jan 01 2015 00:00:00,
  26. * // Fri Jan 01 2016 00:00:00,
  27. * // Sun Jan 01 2017 00:00:00
  28. * // ]
  29. */
  30. export default function eachYearOfInterval(dirtyInterval) {
  31. requiredArgs(1, arguments);
  32. var interval = dirtyInterval || {};
  33. var startDate = toDate(interval.start);
  34. var endDate = toDate(interval.end);
  35. var endTime = endDate.getTime(); // Throw an exception if start date is after end date or if any date is `Invalid Date`
  36. if (!(startDate.getTime() <= endTime)) {
  37. throw new RangeError('Invalid interval');
  38. }
  39. var dates = [];
  40. var currentDate = startDate;
  41. currentDate.setHours(0, 0, 0, 0);
  42. currentDate.setMonth(0, 1);
  43. while (currentDate.getTime() <= endTime) {
  44. dates.push(toDate(currentDate));
  45. currentDate.setFullYear(currentDate.getFullYear() + 1);
  46. }
  47. return dates;
  48. }