-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
90 lines (76 loc) · 2.88 KB
/
index.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
// AsyncDependencyManager
// (c) 2010-02-09 Cortland Klein <me@pixelcort.com>
/*globals exports*/
var sys = require('sys'),
repl = require("repl"),
AsyncDependencyManager;
var console = {log:function(x){sys.puts(x);}};
AsyncDependencyManager = function(tasks) {
var taskName,
task,
prerequisiteTaskNames,
prerequisiteTaskName,
l,
i,
prerequisiteTask,
startTasks;
if (!this instanceof AsyncDependencyManager) return new AsyncDependencyManager(tasks);
this.tasks = tasks;
this.startTasks = {};
for (taskName in tasks) { if (!tasks.hasOwnProperty(taskName)) continue;
task = tasks[taskName];
if (!task.name) { // Has no prerequisites
this.startTasks[taskName] = task;
continue;
}
prerequisiteTaskNames = task.name.split('_');
for (i=0,l=prerequisiteTaskNames.length;i<l;i++) {
prerequisiteTaskName = prerequisiteTaskNames[i];
// console.log('prerequisiteTaskName: ' + prerequisiteTaskName);
prerequisiteTask = tasks[prerequisiteTaskName];
// Ensure task and prerequisiteTask have parents and children arrays
if (!prerequisiteTask.hasOwnProperty('children')) prerequisiteTask.children = {};
if (!task.hasOwnProperty('parents')) task.parents = {};
// Setup pointers between two tasks
task.parents[prerequisiteTaskName] = prerequisiteTask;
prerequisiteTask.children[taskName] = task;
sys.puts('task ' + taskName + ' depends on ' + prerequisiteTaskName);
}
}
for (taskName in this.startTasks) { if (!this.startTasks.hasOwnProperty(taskName)) continue;
task = this.startTasks[taskName];
this.callTask(task);
}
};
AsyncDependencyManager.prototype.callTask = function(task, parentCallbacksArguments) {
var manager = this,
taskCallback = function() {
var childTaskName,
parentTaskName,
childTask,
parentTask,
readyToCall,
parentCallbacksArguments;
task.isComplete = true;
task.callbackArguments = arguments;
if (!task.children) return; // Task has no children.
for (childTaskName in task.children) { if (!task.children.hasOwnProperty(childTaskName)) continue;
childTask = task.children[childTaskName];
readyToCall = true;
parentCallbacksArguments = {};
for (parentTaskName in childTask.parents) { if (!childTask.parents.hasOwnProperty(parentTaskName)) continue;
parentTask = childTask.parents[parentTaskName];
if (!parentTask.isComplete) {
readyToCall = false;
break;
} else {
parentCallbacksArguments[parentTaskName] = parentTask.callbackArguments;
}
}
if (readyToCall) manager.callTask(childTask, parentCallbacksArguments);
}
};
task.call(taskCallback, parentCallbacksArguments);
};
///////////////////////////////
exports.AsyncDependencyManager = AsyncDependencyManager;