Public
Edited
Dec 8, 2022
1 fork
1 star
Insert cell
Insert cell
Insert cell
import { Sunburst } from "@d3/sunburst"
Insert cell
part2 = {
const root = sized(tree(data));
const unused = 70000000 - root[s];
const needed = 30000000 - unused;

const enough = d3.min(d3.filter(dirs(root), (d) => d[s] >= needed), d => d[s]);

return { unused, needed, enough };
}
Insert cell
part1 = d3.sum(d3.filter(dirs(sized(tree(data))), d => d[s] <= 100_000), d => d[s])
Insert cell
function* dirs(node) {
yield node;
for (const [name, child] of Object.entries(node))
if (name !== ".." && typeof child === "object") yield* dirs(child);
}
Insert cell
sized = (node) => {
(function size(node) {
return (node[s] ??= d3.sum(Object.entries(node), ([name, child]) =>
name === ".." ? 0 : typeof child === "number" ? child : size(child)
));
})(node);
return node;
}
Insert cell
s = Symbol("size")
Insert cell
tree = (data) => {
let root = {};
let cwd = root;
for (const { command, output } of parse(data)) {
const [, cmd, ...args] = command.split(/\s+/);
switch (cmd) {
case "cd":
const [dir] = args;
cwd[dir] = cwd[dir] || {};
cwd = cwd[dir];
if (dir === "/") root = cwd;
break;
case "ls":
for (const line of output) {
const [size, name] = line.split(/\s+/);
cwd[name] = cwd[name] || (size === "dir" ? { "..": cwd } : +size);
}
break;
default:
throw new Error(`unknown command: ${command}`);
}
}
return root;
}
Insert cell
function* parse(input) {
let block;
for (const line of input.trim().split("\n")) {
if (block) yield block;
if (line.startsWith("$ ")) block = { command: line, output: [] };
else block.output.push(line);
}
yield block;
}
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more