-
Notifications
You must be signed in to change notification settings - Fork 0
/
[56-w12-d1]graph.js
81 lines (67 loc) · 1.9 KB
/
[56-w12-d1]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
function Graph(edgeDirection) {
this.edgeDirection = edgeDirection;
this.nodes = {};
const Node = function (value) {
this.value = value;
this.adjacents = [];
this.addAdjacent = function (node) {
this.adjacents.push(node);
};
this.removeAdjacents = function (node) {
this.adjacents = this.adjacents.filter(adjacent => adjacent !== node);
return node;
};
this.getAdjacents = function () {
return this.adjacents;
};
this.isAdjacent = function (node) {
return this.adjacents.includes(node);
};
};
this.addEdge = function (source, destination) {
const sourceNode = this.addVertex(source);
const destinationNode = this.addVertex(destination);
sourceNode.addAdjacent(destinationNode);
if (this.edgeDirection === 'undirected') {
destinationNode.addAdjacent(sourceNode);
}
return [sourceNode, destinationNode];
};
this.addVertex = function (value) {
if (value in this.nodes) {
return this.nodes[value];
}
const vertex = new Node(value);
this.nodes[value] = vertex;
return vertex;
};
this.removeVertex = function (value) {
//check if vertex is in Graph
//if not return false
//if in graph
//remove it from all other vertices adjacents
//remove it from graph
if (!(value in this.nodes)) {
return false;
}
for (const node in this.nodes) {
console.log(this.nodes[node]);
this.nodes[node].removeAdjacents(this.nodes[value]);
}
delete this.nodes[value];
return true;
};
this.removeEdge = function (source, destination) {
const sourceNode = this.nodes[source];
const destinationNode = this.nodes[destination];
if (sourceNode && destinationNode && sourceNode.isAdjacent(destinationNode)) {
sourceNode.removeAdjacents(destinationNode);
if (this.edgeDirection === 'undirected') {
destinationNode.removeAdjacents(sourceNode);
}
return [source, destination];
}
return false;
};
}
const graph = new Graph('directed');