function defragFiles(xs) {
const expand = (n, i) => Array(n).fill(i);
const rles = xs.filter((_, i) => !(i % 2)).map((rle, i) => [rle, i]);
const gaps = xs.filter((_, i) => i % 2).map((gap) => [gap, []]);
for (let i = rles.length - 1; i > 0; i--) {
for (let j = 0; j < i; j++) {
if (rles[i][0] <= gaps[j][0]) {
gaps[j][0] -= rles[i][0];
gaps[j][1].push(expand(...rles[i]));
rles[i][1] = 0;
break;
}
}
}
const out = [];
for (let j = 0; j < gaps.length; j++) {
out.push(expand(...rles[j]));
out.push(...gaps[j][1]);
out.push(expand(gaps[j][0], 0));
}
return d3.sum(out.flat(), (n, i) => n * i);
}