forked from inolen/quakejs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdirected-graph.js
80 lines (62 loc) · 1.58 KB
/
directed-graph.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
77
78
79
80
function DirectedGraph() {
this._vertices = {};
this._edges = {};
}
DirectedGraph.prototype.getVertices = function () {
var self = this;
return Object.keys(this._vertices).map(function (key) { return self._vertices[key]; });
};
DirectedGraph.prototype.getVertex = function (id) {
return this._vertices[id]
};
DirectedGraph.prototype.addVertex = function (id, data) {
var v = this._vertices[id] = new Vertex(id);
if (data) {
Object.keys(data).forEach(function (key) {
v.data[key] = data[key];
});
}
return v;
};
DirectedGraph.prototype.addEdge = function (a, b) {
var id = a.id + '-' + b.id;
var e = this._edges[id] = new Edge(id, a, b);
a.outEdges.push(e);
b.inEdges.push(e);
return e;
};
DirectedGraph.prototype.removeEdge = function (e) {
var outIdx = e.outVertex.outEdges.indexOf(e);
if (outIdx === -1) {
throw new Error('edge not found on out vertex');
}
var inIdx = e.inVertex.inEdges.indexOf(e);
if (inIdx === -1) {
throw new Error('edge not found on in vertex');
}
e.outVertex.outEdges.splice(outIdx, 1);
e.inVertex.inEdges.splice(inIdx, 1);
delete this._edges[e.id];
};
function Vertex(id) {
this.id = id;
this.data = {};
this.inEdges = [];
this.outEdges = [];
}
Vertex.prototype.getOutVertices = function () {
return this.outEdges.map(function (inE) {
return inE.inVertex;
});
};
Vertex.prototype.getInVertices = function () {
return this.inEdges.map(function (inE) {
return inE.outVertex;
});
};
function Edge(id, outVertex, inVertex) {
this.id = id;
this.outVertex = outVertex;
this.inVertex = inVertex;
}
module.exports = DirectedGraph;