-
Notifications
You must be signed in to change notification settings - Fork 0
/
graph.js
79 lines (57 loc) · 1.84 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
//
let MakeGraph = () =>{
let graph = {};
graph.contains = (node) =>{
return !!graph[node]; //double !! to return only true/false and not the value
}
graph.addVertex = (node) => {
if(!graph.contains(node)){
graph[node] = {edges: {}};
}
}
graph.removeVertex = (node) => {
if(graph.contains(node)){
for(let connectedNode in graph[node].edges) {
graph.removeEdge(node, connectedNode);
}
delete graph[node];
}
}
graph.addEdge = (startNode, endNode) => {
if(graph.contains(startNode) && graph.contains(endNode)){
graph[startNode].edges[endNode] = true;
graph[endNode].edges[startNode] = true;
}
}
graph.removeEdge = (startNode, endNode) => {
if(graph.contains(startNode) && graph.contains(endNode)){
delete graph[startNode].edges[endNode];
delete graph[endNode].edges[startNode];
}
}
graph.hasEdge = (startNode, endNode) => {
return graph.contains(startNode) && graph.contains(endNode) && graph[startNode].edges[endNode] === true
}
return graph;
}
/*let devBook = MakeGraph();
devBook.addVertex('James Gosling');
devBook.addVertex('Guido Rossum');
devBook.addVertex('Linus Torvalds');
devBook.addVertex('Michael Olorunnisola');
console.log("added nodes", devBook);
devBook.addEdge('James Gosling', 'Guido Rossum');
devBook.addEdge('Linus Torvalds', 'Michael Olorunnisola');
console.log("added edges", devBook);
devBook.removeEdge('Linus Torvalds', 'Michael Olorunnisola');
console.log("removed edge", devBook);
devBook.removeVertex('Linus Torvalds');
console.log("removed vertex", devBook);
console.log(devBook.hasEdge('James Gosling', 'Guido Rossum'));
console.log(devBook.hasEdge('James Gosling', 'Michael Olorunnisola'));*/
//addNode is O(1)
//addEdge is O(1)
//removeNode is O(n)
//removeEdge is O(1)
//contains is O(1)
//hasEdge is O(1)