areIntervalsOverlapping.mjs 2.3 KB

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