-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgraph.js
101 lines (91 loc) · 1.94 KB
/
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
var Graph = function(){
this.nodes = [];
}
Graph.prototype.addNode = function(val){
var exists = false;
this.nodes.forEach(function(el){
if(el[0] === val){
exists = true;
}
});
if(!exists){
this.nodes.push([val,[]]);
}
return !exists;
}
Graph.prototype.removeNode = function(val){
var j;
var k;
if(this.getNode(val)){
this.nodes.forEach(function(el, i){
if(el[0] === val){
j = i;
} else {
el[1].forEach(function(edge, ind){
if(edge[0] === val){
k = ind;
}
});
el[1].splice(k,1);
}
});
this.nodes.splice(j,1);
}
}
Graph.prototype.addEdge = function(node1, node2, w, directed){
if(this.getNode(node1) && this.getNode(node2)){
var edges1 = this.getEdges(node1);
var edges2 = this.getEdges(node2);
var found = false;
directed = directed || false;
w = w || 1;
this.nodes.forEach(function(el,i){
if(el[0] === node1){
edges1.forEach(function(edge,j){
if(edge[0] === node2){
this.nodes[i][1][j] = [node2, w];
found = true;
}
},this)
if(!found){
el[1].push([node2, w]);
}
}
},this);
if(!directed){
this.addEdge(node2,node1,w, true);
}
}
}
Graph.prototype.removeEdge = function(node1, node2){
if(this.getNode(node1) && this.getNode(node2)){
this.nodes.forEach(function(el){
if(el[0] === node1){
el[1].forEach(function(edge, i){
if(edge[0] === node2){
el[1].splice(i,1);
}
});
}
});
}
}
Graph.prototype.getEdges = function(node){
var res = null;
this.nodes.forEach(function(el){
if(el[0] === node){
res = el[1];
}
});
return res;
}
Graph.prototype.getNode = function(val){
var res = null;
this.nodes.forEach(function(el){
if(el[0] === val){
res = el;
}
});
return res;
}
//[val,[[edge, w]...]]