Published
Edited
Jul 8, 2019
2 stars
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function recursive_tree_dfs(visit, root, delay) {
// visit our current node
visit(root, delay)
// If the current node has children go and visit them one at a time
// note we are passing a delay along for the d3 animations
// base case is implicity here as it is a node with no children rather than
// a check if we are null
if(root.children) root.children.map(child=> {
delay = recursive_tree_dfs(visit, child, delay+c.animationDuration)
visit(root, delay+=c.animationDuration)
})

// return our delay to our parent
return delay
}
Insert cell
function iterative_tree_dfs(visit, root, delay) {
// dfs uses a stack to keep track of traversals. Initialize the stack with our root
let stack = [root]
// while we still have nodes to explore
while (stack.length > 0) {
// pop off our current node in the stack and visit it
const node = stack.pop()
visit(node, delay+=c.animationDuration);
// if our node has any children, add them to the stack
if(node.children) node.children.map(child=>stack.push(child))
}
}
Insert cell
md `# Graph Examples`
Insert cell
Insert cell
Insert cell
function recursive_graph_dfs(visit, node, nodes, links, visitedNodes, delay) {
visit(node, delay)
// get the nodes where we have an edge connected to the current node
const connectedLinks = links.filter(d=>d.source.id == node.id || d.target.id == node.id)
// get the ids of the nodes we have not visited
const unvistedNodeIds = connectedLinks
.map(link => link.source.id == node.id ? link.target.id: link.source.id)
.filter(nodeId=>visitedNodes.indexOf(nodeId) < 0)
// get the actual node that we have not visited
const unvisitedNodes = unvistedNodeIds.map(id=>nodes.filter(node=>node.id == id)[0])
// loop over the nodes you need to visit and go visit them (passing along the delay for the animation)
// also add the nodes you are visiting to the visted Node list so you don't backtrack.
unvisitedNodes.map(node=>{
visitedNodes.push(node.id)
delay = recursive_graph_dfs(visit, node, nodes, links, visitedNodes, delay+=c.animationDuration)
visit(node, delay+=c.animationDuration)
})
return delay
}
Insert cell
md`# D3 Graphing Logic`
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
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