forked from knaxus/problem-solving-javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
103 lines (85 loc) · 2.08 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
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
102
103
const { LinkedList } = require('../LinkedList');
class Graph {
constructor() {
this.data = this.getStorage();
}
addVertex(v) {
this.data.addVertex(v);
}
addEdge(v, e) {
this.data.addEdge(v, e);
}
removeEdge(v, e) {
this.data.removeEdge(v, e);
}
removeVertex(v) {
this.data.removeVertex(v);
}
getEdges(v) {
return this.data.getEdges(v);
}
display() {
return this.data.displayMatrix();
}
// eslint-disable-next-line class-methods-use-this
getStorage() {
const map = {};
return {
addVertex(v) {
if (!map[v]) map[v] = new LinkedList();
},
addEdge(v, e) {
if (map[v]) {
map[v].addAtEnd(e);
}
},
removeEdge(v, e) {
if (map[v]) {
map[v].filter(e);
}
},
removeVertex(v) {
if (map[v]) {
delete map[v];
const vertices = Object.keys(map);
const edge = v; // this vertex may be an edge for other vertices
vertices.forEach((vertex) => this.removeEdge(vertex, edge));
}
},
getEdges(v) {
if (map[v]) {
return map[v].traverseList();
}
},
displayMatrix() {
const vertices = Object.keys(map);
const result = {};
vertices.forEach((v) => {
result[v] = map[v].traverseList();
});
return result;
},
};
}
}
// const g = new Graph();
// g.addVertex('Noida');
// console.log(g.display());
// g.addEdge('Noida', 'Greater Noida');
// g.addEdge('Noida', 'Ghaziabaad');
// g.addEdge('Noida', 'Meerut');
// g.addEdge('Noida', 'Greater Noida');
// g.addEdge('Noida', 'Mathura');
// g.addVertex('Mathura');
// g.addEdge('Mathura', 'Noida');
// g.addEdge('Mathura', 'Meerut');
// console.log(g.display());
// // g.data['Noida'].size = 10;
// // console.log(g.data['Noida']);
// // g.filter('Noida', 'Greater Noida');
// console.log(g.display());
// console.log('removing Mathura');
// g.removeVertex('Mathura');
// console.log(g.display());
// console.log(g.getEdges('Noida'));
module.exports = Graph;