Skip to content

Instantly share code, notes, and snippets.

@stevekane
Last active August 29, 2015 14:07
Show Gist options
  • Save stevekane/c9611dfa0c79bfe2c45b to your computer and use it in GitHub Desktop.
Save stevekane/c9611dfa0c79bfe2c45b to your computer and use it in GitHub Desktop.
This is an overview of the way a graph object with backwards refs is stored
//Object -> Node -- constructor
let Node = (hash) => {
this.id = hash.id || new UUID()
this.value = hash
this.parentId = null
this.childIds = []
}
//-> Graph -- constructor
let Graph = () => {
this.nodes = {}
}
/*
* We always add the node to the graph before hooking up any relationships!
* Here we are simply taking a list of nodes all of which have an ID and indexing
* them in our graph structure. We will then assign relationships by id
*/
//Graph -> Node -> Void
let addNode = (graph, node) => {
graph.nodes[node.id] = node
}
//Graph -> String -> String -> Void
let attach = (graph, parentId, childId) => {
graph.nodes[parentId].children.push(childId)
graph.nodes[childId].parentId = parentId
}
//Graph -> String -> Void
let detach = (graph, nodeId) => {
let parentId = graph.nodes[nodeId].parentId
graph.nodes[parentId].children.pop(nodeId)
graph.nodes[nodeId] = undefined
}
//(b -> Node) -> b -> Graph -> b
let reduce = (redFn, accum, graph) => {
let keys = Object.keys(graph.node)
for (for i = 0; i < keys.length; ++i){
accum = redFn(accum, graph.nodes[keys[i]])
}
return accum
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment