forked from Graph-Visualization/graph-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfetch_algo.js
75 lines (61 loc) · 1.65 KB
/
fetch_algo.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
const DFS = require('./dfs');
const BFS = require('./bfs');
// This script stores all the function
// which makes request to get the corresponding algo
// This function converts the values
// in the required format for GraphBase
const purifyValue = (graph_val) => {
let vertex = new Set();
graph_val.forEach((value, ind) => {
vertex.add(value.src);
vertex.add(value.dest);
});
return { graph_val, vertex };
};
const getDFS = (graph_val) => {
values = purifyValue(graph_val);
graph_values = values.graph_val;
vertex = values.vertex;
vertex = Array.from(vertex);
let graph = new DFS(vertex.length);
graph.addVertex(vertex);
for (let i = 0; i < graph_values; i++) {
let node = graph_values[i];
graph.addEdge(node.src, node.dest, node.weight);
}
return graph.dfs();
};
const getBFS = (graph_val) => {
values = purifyValue(graph_val);
graph_values = values.graph_val;
vertex = values.vertex;
vertex = Array.from(vertex);
let graph = new BFS(vertex.length);
graph.addVertex(vertex);
for (let i = 0; i < graph_values; i++) {
let node = graph_values[i];
graph.addEdge(node.src, node.dest, node.weight);
}
return graph.bfs();
};
// Prepares the response to be sent back
const prepResponse = (graph_val, algo) => {
let result;
if (algo === 'dfs') {
result = getDFS(graph_val);
} else if (algo === 'bfs') {
result = getBFS(graph_val);
} else if (algo === 'mst') {
result = '';
} else if (algo === 'cycle') {
result = '';
} else {
throw Error('Algorithm not supported!');
}
let resp = {
algo,
result,
};
return JSON.stringify(resp);
};
module.exports = prepResponse;