forked from crizstian/data-structure-and-algorithms-with-ES6
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgraph.module.js
68 lines (63 loc) · 2.07 KB
/
graph.module.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
(function (exports) {
const {bfs, dfs} = require('./graph.search')
const graphFactory = () => {
let graph = {}
let vertices = 0
const graphProto = {
contains: (node) => !!graph[node],
hasEdge: (nodeOne, nodeTwo) => {
if (graphProto.contains(nodeOne) && graphProto.contains(nodeTwo)) {
return !!graph[nodeOne].edges[nodeTwo]
}
},
addVertex: (node) => {
if (!graphProto.contains(node)) {
graph[node] = {edges: {}, visited: false}
vertices += 1
}
},
removeVertex: (node) => {
if (graphProto.contains(node)) {
for (let item in graph[node].edges) {
if (graph[node].edges.hasOwnProperty(item)) {
graph.removeEdge(node, item)
}
}
vertices -= 1
delete graph[node]
}
},
addEdge: (nodeOne, nodeTwo) => {
if (graphProto.contains(nodeOne) && graphProto.contains(nodeTwo)) {
graph[nodeOne].edges[nodeTwo] = true
graph[nodeTwo].edges[nodeOne] = true
}
},
removeEdge: (nodeOne, nodeTwo) => {
if (graphProto.contains(nodeOne) && graphProto.contains(nodeTwo)) {
delete graph[nodeOne].edges[nodeTwo]
delete graph[nodeTwo].edges[nodeOne]
}
},
showGraph: () => {
let show = ''
for (let v in graph) {
show += `${v} -> `
for (let n in graph[v].edges) {
show += n + ', '
}
show += '\n'
}
console.log(show)
},
showVertex: (node) => console.log(graphProto.getVertex(node)),
showVertexs: () => console.log(Object.keys(graph)),
getGraph: () => graph,
getVertex: (node) => (graphProto.contains(node)) ? graph[node] : false,
getNumVertices: () => vertices
}
Object.assign(graphProto, {bfs: bfs.bind(graphProto), dfs: dfs.bind(graphProto)})
return Object.create(graphProto)
}
Object.assign(exports, {graph: graphFactory})
}((typeof module.exports !== undefined) ? module.exports : window))