forked from esnext/es6-module-transpiler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsorting.js
45 lines (42 loc) · 1.04 KB
/
sorting.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
/**
* Determines the execution order of the given modules. This function resolves
* cycles by preserving the order in which the modules are visited.
*
* @param {Module[]} modules
* @return {Module[]}
*/
function sort(modules) {
var result = [];
var state = {};
modules.forEach(function(mod) {
visit(mod, result, state);
});
return result;
}
exports.sort = sort;
/**
* Visits the given module, adding it to `result` after visiting all of the
* modules it imports, recursively. The `state` argument is private and maps
* module ids to the current visit state.
*
* @private
* @param {Module} mod
* @param {Module[]} result
* @param {Object.<string,string>} state
*/
function visit(mod, result, state) {
if (state[mod.id] === 'added') {
// already in the list, ignore it
return;
}
if (state[mod.id] === 'seen') {
// cycle found, just ignore it
return;
}
state[mod.id] = 'seen';
mod.imports.modules.forEach(function(mod) {
visit(mod, result, state);
});
state[mod.id] = 'added';
result.push(mod);
}