I have a questions about dependencies. Having the following object:
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"]}
};
Need a way to create a sequence of all files(letters) in a way, that i will not messed up the dependency order of the files ( f will not come before b and c ). So my idea is to traverse it like i would do graph crawling.
//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);
So the question is: Is my solution perfect? Would it fail in somehow having file, before dependency file?
Aucun commentaire:
Enregistrer un commentaire