javascript
38 lines · 8 steps
Merging overlapping date ranges
Sort intervals by start date, then sweep once to fold overlapping or adjacent ranges into a compact list.
Explained by
highlit
1function mergeDateRanges(ranges) {
2 const parsed = ranges
3 .map(({ start, end }) => ({
4 start: new Date(start),
5 end: new Date(end),
6 }))
7 .filter(({ start, end }) => start <= end)
8 .sort((a, b) => a.start - b.start);
9
10 const merged = [];
11
12 for (const range of parsed) {
13 const last = merged[merged.length - 1];
14
15 if (last && range.start <= addDay(last.end)) {
16 if (range.end > last.end) {
17 last.end = range.end;
18 }
19 } else {
20 merged.push({ ...range });
21 }
22 }
23
24 return merged.map(({ start, end }) => ({
25 start: toISODate(start),
26 end: toISODate(end),
27 }));
28}
29
30function addDay(date) {
31 const next = new Date(date);
32 next.setDate(next.getDate() + 1);
33 return next;
34}
35
36function toISODate(date) {
37 return date.toISOString().slice(0, 10);
38}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Sorting intervals by start turns merging into a single left-to-right pass.
- 2You only ever need to compare each range against the most recent merged one.
- 3Normalizing input early (parsing, filtering) keeps the core algorithm clean and correct.
Related explainers
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
javascript
import { useEffect, useRef, useState } from 'react'; export function useDelayedFlag(active, delay = 300) { const [visible, setVisible] = useState(false);
Delaying a loading spinner with a React hook
custom-hooks
debouncing
cleanup
Intermediate
8 steps
python
import re from functools import total_ordering from typing import Optional
Parsing and comparing semantic versions
regex
operator-overloading
sorting
Intermediate
7 steps
javascript
const SWIPE_THRESHOLD = 80; const MAX_TRANSLATE = 120; export function attachSwipeToDismiss(element, onDismiss) {
Building a swipe-to-dismiss gesture in JS
touch-events
gesture-detection
dom-manipulation
Intermediate
10 steps
java
public final class ImportOrganizer { private static final Pattern IMPORT_LINE = Pattern.compile("^import\\s+(static\\s+)?([\\w.]+(?:\\.\\*)?)\\s*;\\s*$");
Sorting Java imports with a regex pass
regex
sorting
text-processing
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/merging-overlapping-date-ranges-explained-javascript-cdde/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.