index.js 2.1 KB

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