文件依赖项按正确的顺序排列
File Dependencies in right order
我有一个关于依赖的问题。具有以下对象:
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)
相关文章:
- 从数组中删除重复条目,并在javascript中按顺序排列
- Javascript从数组中随机选择并按字母顺序排列
- 如何在php中按元素按字母顺序排列json文件
- 如何根据 js 中每个单词的第 n 个字母按字母顺序排列列表
- Javascript将生日按数组顺序排列
- 列出按字母顺序排列的 javascript 和字母标题
- 按字母顺序排列字符串
- 排列<p>使用jQuery按日期顺序排列的元素
- 确定字符串中的所有字母是否按JavaScript字母顺序排列
- 按数组顺序排列对象
- 按字母顺序排列列表
- 多个 ajax 异步不按顺序排列,需要同步行为
- 按数字顺序排列列表
- JavaScript 按字母顺序排列
- jQuery Rotator是按字母顺序排列的,我怎样才能在我的主页上随机化
- 按字母顺序排列 AngularJS 中对象保留键/值关联的选项
- 需要一个优化的解决方案来获取按字母顺序排列的记录集 javascript
- Jquery - 按顺序排列的 ajax 循环
- Javascript 如何创建按顺序排列数字的对象
- Mongodb文档没有按正确的顺序排列