-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathgraph.js
74 lines (57 loc) · 1.74 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
const graph = {
'you': ['alice', 'bob', 'claire'],
'bob': ['anuj', 'peggy'],
'alice': ['peggy'],
'claire': ['thom', 'jonny'],
'anuj': [],
'peggy': [],
'thom': [],
'jonny': [],
}
class Graph {
/**
* Список вершин и вершин смежных с ними
*/
constructor(list) {
this.store = list || {};
};
/**
* Вывод списка смежных вершин
*/
getList() {
return this.store();
}
/** Добавить вершину */
addVertex(key, value) {
if (!Array.isArray(value) || !key) return;
this.store[key] = value;
}
/** Добавить ребро между вершинами first и second */
addEdge(first, second) {
if (!this.store[first] || !this.store[second]) return;
const firstValid = this.isValid(second, first),
secondValid = this.isValid(first, second);
if (firstValid)
this.addFriends(second, first);
if (secondValid)
this.addFriends(first, second);
}
/** Проверка есть ли среди смежных вершин first
* вершина second и наоборот */
isValid(key, value) {
return this.store[key].indexOf(value) === -1
}
/** Добавляет вершину name в список key */
addFriends(key, name) {
this.store[key].push(name)
}
/** Возвращает список смежных вершин у key */
getVertex(key) {
return this.store[key]
}
}
const mates = new Graph(graph);
mates.addVertex('jimm', [])
mates.addEdge('claire', 'peggy');
console.log(mates.getVertex('claire'));
console.log(mates.getVertex('peggy'));