UNPKG

2.4 kBJavaScriptView Raw
1import { toDate } from "./toDate.mjs";
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 * )
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 */
61export function areIntervalsOverlapping(intervalLeft, intervalRight, options) {
62 const [leftStartTime, leftEndTime] = [
63 +toDate(intervalLeft.start),
64 +toDate(intervalLeft.end),
65 ].sort((a, b) => a - b);
66 const [rightStartTime, rightEndTime] = [
67 +toDate(intervalRight.start),
68 +toDate(intervalRight.end),
69 ].sort((a, b) => a - b);
70
71 if (options?.inclusive)
72 return leftStartTime <= rightEndTime && rightStartTime <= leftEndTime;
73
74 return leftStartTime < rightEndTime && rightStartTime < leftEndTime;
75}
76
77// Fallback for modularized imports:
78export default areIntervalsOverlapping;