-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgraph2dot.js
76 lines (56 loc) · 1.24 KB
/
graph2dot.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
module.exports = g2d
// graph2dot turns a directed graph as an input and returns
// a dot digraph.
//
// The input of the graph is:
// { "node": ["dependency", "dependency", ...] }
//
function g2d(graph) {
// TODO: make this streaming...
var nodes = graphNodes(graph)
var edges = graphEdges(graph)
var out = 'digraph deps {\n';
for (var n in nodes) {
out += dotForNode(nodes[n])
}
out += '\n'
for (var e in edges) {
out += dotForEdge(edges[e])
}
out += '}'
return out
}
function dotSafe(s) {
return s.replace(/[^A-Za-z0-9]/g, '_')
}
function dotForNode(node) {
return ' '+ dotSafe(node) + ' [label="' + node + '"];\n'
}
function dotForEdge(edge) {
return ' '+ dotSafe(edge[0]) + ' -> ' + dotSafe(edge[1]) + ';\n'
}
function graphNodes(graph) {
var nodes = []
var seen = {}
var uniqAdd = function(elem) {
if (seen[elem]) return
nodes.push(elem)
seen[elem] = true
}
for (var n in graph) {
uniqAdd(n)
for (var n2 in graph[n]) {
uniqAdd(graph[n][n2]) // make sure deps are there.
}
}
return nodes
}
function graphEdges(graph) {
var edges = []
for (var n1 in graph) {
for (var n2 in graph[n1]) {
edges.push([graph[n1][n2], n1])
}
}
return edges
}