getOverlappingDaysInIntervals.cjs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. "use strict";
  2. exports.getOverlappingDaysInIntervals = getOverlappingDaysInIntervals;
  3. var _index = require("./_lib/getTimezoneOffsetInMilliseconds.cjs");
  4. var _index2 = require("./constants.cjs");
  5. var _index3 = require("./toDate.cjs");
  6. /**
  7. * @name getOverlappingDaysInIntervals
  8. * @category Interval Helpers
  9. * @summary Get the number of days that overlap in two time intervals
  10. *
  11. * @description
  12. * Get the number of days that overlap in two time intervals. It uses the time
  13. * between dates to calculate the number of days, rounding it up to include
  14. * partial days.
  15. *
  16. * Two equal 0-length intervals will result in 0. Two equal 1ms intervals will
  17. * result in 1.
  18. *
  19. * @param intervalLeft - The first interval to compare.
  20. * @param intervalRight - The second interval to compare.
  21. * @param options - An object with options
  22. *
  23. * @returns The number of days that overlap in two time intervals
  24. *
  25. * @example
  26. * // For overlapping time intervals adds 1 for each started overlapping day:
  27. * getOverlappingDaysInIntervals(
  28. * { start: new Date(2014, 0, 10), end: new Date(2014, 0, 20) },
  29. * { start: new Date(2014, 0, 17), end: new Date(2014, 0, 21) }
  30. * )
  31. * //=> 3
  32. *
  33. * @example
  34. * // For non-overlapping time intervals returns 0:
  35. * getOverlappingDaysInIntervals(
  36. * { start: new Date(2014, 0, 10), end: new Date(2014, 0, 20) },
  37. * { start: new Date(2014, 0, 21), end: new Date(2014, 0, 22) }
  38. * )
  39. * //=> 0
  40. */
  41. function getOverlappingDaysInIntervals(intervalLeft, intervalRight) {
  42. const [leftStart, leftEnd] = [
  43. +(0, _index3.toDate)(intervalLeft.start),
  44. +(0, _index3.toDate)(intervalLeft.end),
  45. ].sort((a, b) => a - b);
  46. const [rightStart, rightEnd] = [
  47. +(0, _index3.toDate)(intervalRight.start),
  48. +(0, _index3.toDate)(intervalRight.end),
  49. ].sort((a, b) => a - b);
  50. // Prevent NaN result if intervals don't overlap at all.
  51. const isOverlapping = leftStart < rightEnd && rightStart < leftEnd;
  52. if (!isOverlapping) return 0;
  53. // Remove the timezone offset to negate the DST effect on calculations.
  54. const overlapLeft = rightStart < leftStart ? leftStart : rightStart;
  55. const left =
  56. overlapLeft - (0, _index.getTimezoneOffsetInMilliseconds)(overlapLeft);
  57. const overlapRight = rightEnd > leftEnd ? leftEnd : rightEnd;
  58. const right =
  59. overlapRight - (0, _index.getTimezoneOffsetInMilliseconds)(overlapRight);
  60. // Ceil the number to include partial days too.
  61. return Math.ceil((right - left) / _index2.millisecondsInDay);
  62. }