areIntervalsOverlapping.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import { toDate } from "./toDate.js";
  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. * { inclusive: true }
  49. * )
  50. * //=> true
  51. */
  52. export function areIntervalsOverlapping(intervalLeft, intervalRight, options) {
  53. const [leftStartTime, leftEndTime] = [
  54. +toDate(intervalLeft.start, options?.in),
  55. +toDate(intervalLeft.end, options?.in),
  56. ].sort((a, b) => a - b);
  57. const [rightStartTime, rightEndTime] = [
  58. +toDate(intervalRight.start, options?.in),
  59. +toDate(intervalRight.end, options?.in),
  60. ].sort((a, b) => a - b);
  61. if (options?.inclusive)
  62. return leftStartTime <= rightEndTime && rightStartTime <= leftEndTime;
  63. return leftStartTime < rightEndTime && rightStartTime < leftEndTime;
  64. }
  65. // Fallback for modularized imports:
  66. export default areIntervalsOverlapping;