eachDayOfInterval.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import { normalizeInterval } from "./_lib/normalizeInterval.js";
  2. import { constructFrom } from "./constructFrom.js";
  3. /**
  4. * The {@link eachDayOfInterval} function options.
  5. */
  6. /**
  7. * The {@link eachDayOfInterval} function result type. It resolves the proper data type.
  8. * It uses the first argument date object type, starting from the date argument,
  9. * then the start interval date, and finally the end interval date. If
  10. * a context function is passed, it uses the context function return type.
  11. */
  12. /**
  13. * @name eachDayOfInterval
  14. * @category Interval Helpers
  15. * @summary Return the array of dates within the specified time interval.
  16. *
  17. * @description
  18. * Return the array of dates within the specified time interval.
  19. *
  20. * @typeParam IntervalType - Interval type.
  21. * @typeParam Options - Options type.
  22. *
  23. * @param interval - The interval.
  24. * @param options - An object with options.
  25. *
  26. * @returns The array with starts of days from the day of the interval start to the day of the interval end
  27. *
  28. * @example
  29. * // Each day between 6 October 2014 and 10 October 2014:
  30. * const result = eachDayOfInterval({
  31. * start: new Date(2014, 9, 6),
  32. * end: new Date(2014, 9, 10)
  33. * })
  34. * //=> [
  35. * // Mon Oct 06 2014 00:00:00,
  36. * // Tue Oct 07 2014 00:00:00,
  37. * // Wed Oct 08 2014 00:00:00,
  38. * // Thu Oct 09 2014 00:00:00,
  39. * // Fri Oct 10 2014 00:00:00
  40. * // ]
  41. */
  42. export function eachDayOfInterval(interval, options) {
  43. const { start, end } = normalizeInterval(options?.in, interval);
  44. let reversed = +start > +end;
  45. const endTime = reversed ? +start : +end;
  46. const date = reversed ? end : start;
  47. date.setHours(0, 0, 0, 0);
  48. let step = options?.step ?? 1;
  49. if (!step) return [];
  50. if (step < 0) {
  51. step = -step;
  52. reversed = !reversed;
  53. }
  54. const dates = [];
  55. while (+date <= endTime) {
  56. dates.push(constructFrom(start, date));
  57. date.setDate(date.getDate() + step);
  58. date.setHours(0, 0, 0, 0);
  59. }
  60. return reversed ? dates.reverse() : dates;
  61. }
  62. // Fallback for modularized imports:
  63. export default eachDayOfInterval;