-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
49 lines (35 loc) · 1008 Bytes
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
var graphlib = require("graphlib");
var par = require("par");
var prop = require("prop");
var Graph = graphlib.Graph;
module.exports = toGraph;
function toGraph(json) {
var graphDefinitions = json.graphs;
if (graphDefinitions) return graphDefinitions.map(makeGraph);
var graphDefinition = json.graph;
if (graphDefinition)
return makeGraph(graphDefinition);
throw new TypeError("No graphs defined");
}
function makeGraph(graphDefinition) {
var nodes = graphDefinition.nodes || [];
var edges = graphDefinition.edges || [];
var directed = graphDefinition.directed || edges.some(prop("directed"));
var graph = new Graph({
directed: directed,
multigraph: true
});
nodes.forEach(par(addNode, graph));
edges.forEach(par(addEdge, graph));
return graph;
}
function addNode(graph, node) {
var id = node.id;
graph.setNode(id, node);
}
function addEdge(graph, edge) {
var source = edge.source;
var target = edge.target;
var id = edge.id;
graph.setEdge(source, target, edge, id);
}