areIntervalsOverlapping.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. "use strict";
  2. exports.areIntervalsOverlapping = areIntervalsOverlapping;
  3. var _index = require("./toDate.js");
  4. /**
  5. * The {@link areIntervalsOverlapping} function options.
  6. */
  7. /**
  8. * @name areIntervalsOverlapping
  9. * @category Interval Helpers
  10. * @summary Is the given time interval overlapping with another time interval?
  11. *
  12. * @description
  13. * Is the given time interval overlapping with another time interval? Adjacent intervals do not count as overlapping unless `inclusive` is set to `true`.
  14. *
  15. * @param intervalLeft - The first interval to compare.
  16. * @param intervalRight - The second interval to compare.
  17. * @param options - The object with options
  18. *
  19. * @returns Whether the time intervals are overlapping
  20. *
  21. * @example
  22. * // For overlapping time intervals:
  23. * areIntervalsOverlapping(
  24. * { start: new Date(2014, 0, 10), end: new Date(2014, 0, 20) },
  25. * { start: new Date(2014, 0, 17), end: new Date(2014, 0, 21) }
  26. * )
  27. * //=> true
  28. *
  29. * @example
  30. * // For non-overlapping time intervals:
  31. * areIntervalsOverlapping(
  32. * { start: new Date(2014, 0, 10), end: new Date(2014, 0, 20) },
  33. * { start: new Date(2014, 0, 21), end: new Date(2014, 0, 22) }
  34. * )
  35. * //=> false
  36. *
  37. * @example
  38. * // For adjacent time intervals:
  39. * areIntervalsOverlapping(
  40. * { start: new Date(2014, 0, 10), end: new Date(2014, 0, 20) },
  41. * { start: new Date(2014, 0, 20), end: new Date(2014, 0, 30) }
  42. * )
  43. * //=> false
  44. *
  45. * @example
  46. * // Using the inclusive option:
  47. * areIntervalsOverlapping(
  48. * { start: new Date(2014, 0, 10), end: new Date(2014, 0, 20) },
  49. * { start: new Date(2014, 0, 20), end: new Date(2014, 0, 24) }
  50. * )
  51. * //=> false
  52. *
  53. * @example
  54. * areIntervalsOverlapping(
  55. * { start: new Date(2014, 0, 10), end: new Date(2014, 0, 20) },
  56. * { start: new Date(2014, 0, 20), end: new Date(2014, 0, 24) },
  57. * { inclusive: true }
  58. * )
  59. * //=> true
  60. */
  61. function areIntervalsOverlapping(intervalLeft, intervalRight, options) {
  62. const [leftStartTime, leftEndTime] = [
  63. +(0, _index.toDate)(intervalLeft.start),
  64. +(0, _index.toDate)(intervalLeft.end),
  65. ].sort((a, b) => a - b);
  66. const [rightStartTime, rightEndTime] = [
  67. +(0, _index.toDate)(intervalRight.start),
  68. +(0, _index.toDate)(intervalRight.end),
  69. ].sort((a, b) => a - b);
  70. if (options?.inclusive)
  71. return leftStartTime <= rightEndTime && rightStartTime <= leftEndTime;
  72. return leftStartTime < rightEndTime && rightStartTime < leftEndTime;
  73. }