Public
Edited
Apr 28, 2023
Insert cell
Insert cell
{
const edges = [
{ source: "root", target: "1"},
{ source: "root", target: "2"},
{ source: "root", target: "3"},
{ source: "1", target: "4"},
{ source: "2", target: "5"},
{ source: "5", target: "root"},
]
const map = buildAdjacencyMap(edges)
const list = traverseDepthFirst(map, "root")
const build = d3.stratify()
.parentId(d => d.source)
.id(d => d.target)
return build(list)
}
Insert cell
traverseDepthFirst = (map, root) => {
const isNotVisited = (node, path) => {
return path.every(pathNode => pathNode !== node)
}

const edges = []
const visit = (source, target, path) => {
edges.push({ source, target })
const children = map.get(target) ?? []
children.forEach(child => {
if (isNotVisited(child, path)) {
visit(target, child, [...path, child])
}
})
}

const ROOT = ""
visit(ROOT, root, [root])

return edges
}
Insert cell
buildAdjacencyMap = edges => {
const getSource = d => d.source
const getTarget = d => d.target

const map = new Map()
edges.forEach(edge => {
const source = getSource(edge)
const target = getTarget(edge)

const targets = map.get(source) ?? []
map.set(source, [...targets, target])
})
return map
}
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