文件依赖项按正确的顺序排列

File Dependencies in right order

本文关键字:顺序 排列 依赖 文件      更新时间:2023-09-26

我有一个关于依赖的问题。具有以下对象:

var files = {
    "f": {"dep": ["b", "c"]},
    "g": {"dep": ["e", "f"]},
    "a": {"dep": ["c", "b"]},
    "b": {"dep": ["d", "c"]},
    "c": {"dep": []},
    "d": {"dep": ["c"]},
    "e": {"dep": ["a"]}
};

需要一种方法来创建所有文件(字母)的序列,这样我就不会弄乱文件的依赖顺序(f不会在b和c之前)。所以我的想法是像做图形爬行一样遍历它。

//TODO -o :if we have e.g "a" depend on "b" and "b" depend on "a" this will lead to
//TODO -o :infinite recursion - so we should handle this scenario.
//Todo -o :It could be optimized by checking if the file is already visited.
//stores all files in dependant order
var filesInDependantOrder = [];
//loop through all files
for (var file in files)
{
    //call the drillDownDependencies to drill down to all files
    drillDownDependencies( files[file] );
    //we exit from the recursion drillDownDependencies and add the file that we have passed
    //if not exists
    if (filesInDependantOrder.indexOf( file ) < 0) {
        filesInDependantOrder.push( file );
    }
}
function drillDownDependencies( root )
{
    //loop through all dependencies of the given file
    for (var i = 0, ilen = root["dep"].length; i < ilen; i++)
    {
        //pass the dependency to check if the given
        //dependency has dependencies by its own
        drillDownDependencies( files[root["dep"][i]] );
        //we exit from the recursion if the dependency
        //don't have other dependencies
        if (filesInDependantOrder.indexOf( root["dep"][i] ) < 0)
        {
            //push the dependency that don't have
            //other dependencies if not exists
            filesInDependantOrder.push( root["dep"][i] );
        }
    }
}
console.log(filesInDependantOrder);

所以问题是:我的解决方案是完美的吗?它会以某种方式在依赖文件之前有文件失败吗?我想不出会落在脸上的场景。

-

-提前向人们建议我一些AMD的实施(如require.js) - 它不适合我的情况。

我认为只要您没有循环依赖项,您的解决方案就会起作用。

供您参考,此过程称为拓扑排序。 wiki 页面包含的算法将有效地执行排序并检测循环依赖关系:

L ← Empty list that will contain the sorted elements
S ← Set of all nodes with no incoming edges
while S is non-empty do
    remove a node n from S
    add n to tail of L
    for each node m with an edge e from n to m do
        remove edge e from the graph
        if m has no other incoming edges then
            insert m into S
if graph has edges then
    return error (graph has at least one cycle)
else 
    return L (a topologically sorted order)