1function rectangleArea(rects) {
2 const events = [];
3 for (const [x1, y1, x2, y2] of rects) {
4 events.push([x1, 0, y1, y2]);
5 events.push([x2, 1, y1, y2]);
6 }
7 events.sort((a, b) => a[0] - b[0]);
8 let area = 0, prevX = events[0][0];
9 const active = [];
10 for (const [x, type, y1, y2] of events) {
11 area += coveredLength(active) * (x - prevX);
12 if (type === 0) active.push([y1, y2]);
13 else active.splice(active.findIndex(s => s[0] === y1 && s[1] === y2), 1);
14 prevX = x;
15 }
16 return area;
17}
18function coveredLength(intervals) {
19 const sorted = [...intervals].sort((a, b) => a[0] - b[0]);
20 let len = 0, end = -Infinity;
21 for (const [s, e] of sorted)
22 if (e > end) { len += e - Math.max(s, end); end = e; }
23 return len;
24}