index.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = eachYearOfInterval;
  6. var _index = _interopRequireDefault(require("../toDate/index.js"));
  7. var _index2 = _interopRequireDefault(require("../_lib/requiredArgs/index.js"));
  8. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  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. * var 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(); // Throw an exception if start date is after end date or if any date is `Invalid Date`
  42. if (!(startDate.getTime() <= endTime)) {
  43. throw new RangeError('Invalid interval');
  44. }
  45. var dates = [];
  46. var currentDate = startDate;
  47. currentDate.setHours(0, 0, 0, 0);
  48. currentDate.setMonth(0, 1);
  49. while (currentDate.getTime() <= endTime) {
  50. dates.push((0, _index.default)(currentDate));
  51. currentDate.setFullYear(currentDate.getFullYear() + 1);
  52. }
  53. return dates;
  54. }
  55. module.exports = exports.default;