-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
45 lines (40 loc) · 1.2 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
function isInRange(interval, newInterval) {
const [startLeft, endLeft] = interval;
const [startRight, endRight] = newInterval;
if (startLeft >= startRight && startLeft <= endRight) return true;
if (endLeft >= startRight && endLeft <= endRight) return true;
if (
startRight >= startLeft &&
startRight <= endLeft &&
endRight >= startLeft &&
endRight <= endRight
)
return true;
return false;
}
export function insert(intervals, newInterval) {
let output = [],
i = 0;
let inRange = null;
while (i < intervals.length) {
const interval = intervals[i];
if (isInRange(interval, newInterval)) {
inRange = true;
newInterval = [
Math.min(interval[0], newInterval[0]),
Math.max(interval[1], newInterval[1]),
];
} else {
if (inRange) {
output.push(newInterval);
newInterval = [];
inRange = false;
}
output.push(interval);
inRange = null;
}
i++;
}
if (inRange !== null || newInterval.length) output.push(newInterval);
return output;
}