-
Notifications
You must be signed in to change notification settings - Fork 0
/
solution.js
40 lines (36 loc) · 878 Bytes
/
solution.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
const sortIntervals = ([aStart, aEnd], [bStart, bEnd]) =>
aStart > bStart || (aStart === bStart && aEnd > bEnd)
? 1
: -1;
const doIntersect = ([aStart, aEnd], [bStart, bEnd]) =>
aStart <= bEnd && aEnd >= bStart;
const combineIntervals = (
[aStart, aEnd],
[bStart, bEnd],
) => [Math.min(aStart, bStart), Math.max(aEnd, bEnd)];
const solution = (intervals) =>
intervals
.sort(sortIntervals)
.reduce(
(merged, currentSeg) =>
merged.some((seg) => doIntersect(seg, currentSeg))
? merged.map((seg) =>
doIntersect(seg, currentSeg)
? combineIntervals(seg, currentSeg)
: seg,
)
: [...merged, currentSeg],
[],
);
(() => {
console.log(
solution([
[2, 4],
[9, 13],
[3, 5],
[1, 3],
[5, 7],
[1, 2],
]),
);
})();