function pack(circles) {
const n = circles.length;
if (!n) return circles;
let a, b, c;
a = circles[0], a.x = 0, a.y = 0;
if (!(n > 1)) return circles;
b = circles[1], a.x = -b.r, b.x = a.r, b.y = 0;
if (!(n > 2)) return circles;
place(b, a, c = circles[2]);
a = new Node(a), b = new Node(b), c = new Node(c);
a.next = c.previous = b;
b.next = a.previous = c;
c.next = b.previous = a;
pack: for (let i = 3; i < n; ++i) {
place(a._, b._, c = circles[i]), c = new Node(c);
let j = b.next, k = a.previous, sj = b._.r, sk = a._.r;
do {
if (sj <= sk) {
if (intersects(j._, c._)) {
b = j, a.next = b, b.previous = a, --i;
continue pack;
}
sj += j._.r, j = j.next;
} else {
if (intersects(k._, c._)) {
a = k, a.next = b, b.previous = a, --i;
continue pack;
}
sk += k._.r, k = k.previous;
}
} while (j !== k.next);
c.previous = a, c.next = b, a.next = b.previous = b = c;
let aa = score(a), ca;
while ((c = c.next) !== b) {
if ((ca = score(c)) < aa) {
a = c, aa = ca;
}
}
b = a.next;
}
return circles;
}