function dodge(data, {radius = 1, x = d => d} = {}) {
const radius2 = radius ** 2;
const circles = data.map((d, i, data) => ({x: +x(d, i, data), data: d})).sort((a, b) => a.x - b.x);
const epsilon = 1e-3;
let head = null, tail = null;
function intersects(x, y) {
let a = head;
while (a) {
if (radius2 - epsilon > (a.x - x) ** 2 + (a.y - y) ** 2) {
return true;
}
a = a.next;
}
return false;
}
for (const b of circles) {
while (head && head.x < b.x - radius2) head = head.next;
if (intersects(b.x, b.y = 0)) {
let a = head;
b.y = Infinity;
do {
let y = a.y + Math.sqrt(radius2 - (a.x - b.x) ** 2);
if (y < b.y && !intersects(b.x, y)) b.y = y;
a = a.next;
} while (a);
}
b.next = null;
if (head === null) head = tail = b;
else tail = tail.next = b;
}
return circles;
}