-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodule.js
More file actions
44 lines (35 loc) · 1.2 KB
/
Copy pathmodule.js
File metadata and controls
44 lines (35 loc) · 1.2 KB
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
/**
* Merges discontinuous time ranges within a given threshold.
*
* @param {Array<[number, number]>} ranges - Array of [start, end) ranges (unsorted, may overlap)
* @param {number} threshold - Max gap (in ms) allowed between ranges to still be merged
* @returns {Array<[number, number]>} - Sorted, non-overlapping merged ranges
*/
const mergeTimeRanges = (ranges, threshold) => {
if (!Array.isArray(ranges) || ranges.length === 0) {
return [];
}
// Step 1: Sort by start time
const sorted = ranges.slice().sort((a, b) => a[0] - b[0]);
const merged = [];
let [currentStart, currentEnd] = sorted[0];
// Step 2: Merge overlapping or close ranges
for (let i = 1; i < sorted.length; i++) {
const [nextStart, nextEnd] = sorted[i];
if (nextStart <= currentEnd + threshold) {
// Merge
currentEnd = Math.max(currentEnd, nextEnd);
} else {
// Push current range and move on
merged.push([currentStart, currentEnd]);
currentStart = nextStart;
currentEnd = nextEnd;
}
}
// Step 3: Push the final range
merged.push([currentStart, currentEnd]);
return merged;
};
module.exports = {
mergeTimeRanges
};