Merge overlapping clips into coverage blocks, bridging gaps
A video editor shows a thin “coverage” bar above the timeline: every stretch of time that has at least one clip is drawn as one solid block. Clips can be dropped on any track, so they overlap freely. Tiny gaps between clips look like flicker on the bar, so the editor also lets the user bridge gaps up to a chosen size.
Implement mergeTimeline(clips, maxGap). It merges the clips into coverage blocks and reports how many clips each block contains.
mergeTimeline(clips, maxGap?) // => Array<{ start, end, count }>
clips is an array of [start, end] pairs of finite numbers (seconds), in any order. start <= end. Zero-length clips such as [5, 5] are allowed, and numbers can be negative or fractional.maxGap is the largest gap to bridge. It defaults to 0. It must be a number that is not negative (Infinity is allowed). Otherwise throw a RangeError.start. A clip joins the current block when clip.start - block.end <= maxGap. Overlapping clips have a negative gap, and clips that touch ([1, 4] and [4, 6]) have a gap of 0, so both always merge.start to its latest end. A clip inside another clip does not shorten the block.count is the number of input clips in that block.start, as new objects with exactly the keys start, end and count. Return [] for no clips.clips or its pairs.const clips = [[0, 4], [10, 12], [3, 6], [6.5, 8], [20, 25]];
mergeTimeline(clips);
// => [
// { start: 0, end: 6, count: 2 },
// { start: 6.5, end: 8, count: 1 },
// { start: 10, end: 12, count: 1 },
// { start: 20, end: 25, count: 1 },
// ]
mergeTimeline(clips, 1);
// => [
// { start: 0, end: 8, count: 3 }, (gap 6 → 6.5 is bridged)
// { start: 10, end: 12, count: 1 }, (gap 8 → 10 is 2 seconds)
// { start: 20, end: 25, count: 1 },
// ]
mergeTimeline([[1, 10], [2, 3], [4, 4]]);
// => [{ start: 1, end: 10, count: 3 }]
mergeTimeline([[1, 2]], -1); // throws RangeError