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