Graph Builder
A graph builder library for modeling, and traversing abstract graph structures.
This is a (incomplete) port of the guava graph library.
The main entry point for building the graph are the
GraphBuilder
for building a
MutableGraph
and
ValueGraphBuilder
for building a
MutableValueGraph
.
Graph Traversal
There is also a traverser
which can perform different types of traversal of any graphs/trees (that implement
SuccessorFunction,
which all the Graphs created by the
GraphBuilder do).
Examples
Creating a Graph
Create an undirected Mutablegraph:
const { GraphBuilder } = require('graph-builder');
const graph = GraphBuilder.undirected().allowsSelfLoops(true).build();
Add some nodes:
graph.addNode("bread");
Add some edges (silently adds nodes too):
graph.putEdge("bread", "bread");
graph.putEdge("chocolate", "peanut butter");
graph.putEdge("peanut butter", "jelly");
Remove an edge:
graph.removeEdge("chocolate", "peanut butter");
Reading From the Graph
Everything returned is iterable.
Get connected nodes:
for (const n of graph.adjacentNodes("peanut butter")) {
console.log(n);
}
Get all the edges:
for (const e of graph.edges()) {
console.log(e.nodeU, ' => ', e.nodeV);
}
Get all edges connected to "peanut butter":
for (const e of graph.incidentEdges("peanut butter")) {
console.log(e.nodeU, ' => ', e.nodeV);
}
Get all the successors/predecessors of "peanut butter" (in an undirected graph, these are the same):
for (const n of graph.successors("peanut butter")) {
console.log(n);
}
for (const n of graph.predecessors("peanut butter")) {
console.log(n);
}
Or for a directed graph:
const graph = GraphBuilder.directed().allowsSelfLoops(true).build();
graph.putEdge("bread", "bread");
graph.putEdge("chocolate", "peanut butter");
graph.putEdge("peanut butter", "jelly");
for (const n of graph.successors("peanut butter")) {
console.log(n);
}
for (const n of graph.predecessors("peanut butter")) {
console.log(n);
}
More
See the full API
documentation for usage.
Full typescript
typings are also provided.