-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
46 lines (41 loc) · 1.28 KB
/
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
class Graph {
constructor() {
this.vertices = {};
}
// Add a new vertex to the graph
addVertex(vertex) {
if (!this.vertices[vertex]) {
this.vertices[vertex] = [];
}
}
// Add an edge between two vertices
addEdge(vertex1, vertex2) {
if (this.vertices[vertex1] && this.vertices[vertex2]) {
this.vertices[vertex1].push(vertex2);
this.vertices[vertex2].push(vertex1);
}
}
// Remove a vertex from the graph
removeVertex(vertex) {
if (this.vertices[vertex]) {
delete this.vertices[vertex];
for (let key in this.vertices) {
const index = this.vertices[key].indexOf(vertex);
if (index !== -1) {
this.vertices[key].splice(index, 1);
}
}
}
}
// Remove an edge between two vertices
removeEdge(vertex1, vertex2) {
if (this.vertices[vertex1] && this.vertices[vertex2]) {
this.vertices[vertex1] = this.vertices[vertex1].filter(v => v !== vertex2);
this.vertices[vertex2] = this.vertices[vertex2].filter(v => v !== vertex1);
}
}
// Display the graph structure
display() {
console.log(this.vertices);
}
}