-
Notifications
You must be signed in to change notification settings - Fork 1
/
DEPENDENCY.js
104 lines (91 loc) · 1.82 KB
/
DEPENDENCY.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
104
function taskA(done) {
console.log("Calling A");
console.log("Task A Completed");
done();
}
function taskB(done) {
console.log("Calling B");
setTimeout(function () {
console.log("Task B Completed");
done();
}, 2000);
}
function taskC(done) {
console.log("Calling c");
setTimeout(function () {
console.log("Task C Completed");
done();
}, 200);
}
function taskD(done) {
console.log("Calling D");
console.log("Task D Completed");
done();
}
function taskE(done) {
console.log("Calling E");
console.log("Task E Completed");
done();
}
const asyncGraph = {
a: {
task: taskA,
},
b: {
task: taskB,
},
c: {
task: taskC,
},
d: {
dependency: ["a", "b"],
task: taskD,
},
e: {
dependency: ["c", "d"],
task: taskE,
},
};
// a
// a -> d
// a -> d -> b
// a -> d -> b -> c -> e
function runAsyncGraph(graph, callback) {
const visited = new Set();
const executionOrder = [];
// Perform DFS to get the topological order
function dfs(node) {
if (visited.has(node)) return;
visited.add(node);
const { dependency } = graph[node];
if (dependency) {
dependency.forEach((dep) => dfs(dep));
}
executionOrder.push(node);
}
// Execute tasks in topological order
function executeTasks(index) {
if (index >= executionOrder.length) {
if (callback) callback();
return;
}
const node = executionOrder[index];
const task = graph[node].task;
task(() => {
executeTasks(index + 1);
});
}
// Start DFS for each node to ensure all nodes are visited
for (const node in graph) {
dfs(node);
}
// Start executing tasks
executeTasks(0);
}
// Example usage:
runAsyncGraph(asyncGraph, () => {
console.log("All tasks completed");
});
// runAsyncGraph(asyncGraph, () => {
// console.log("done");
// });