I need assistance with handling dependencies in a specific object structure. In the given object below:
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"]}
};
I am trying to create a sequence of all files (letters) while maintaining the correct dependency order (ensuring 'f' does not come before 'b' and 'c'). I am considering approaching this like graph traversal.
//TODO -o : Handling scenarios where there might be circular dependencies.
//Todo -o : Optimizing by checking for already visited files.
//Array to store files in dependent order
var filesInDependantOrder = [];
//Iterating through all files
for (var file in files)
{
//Calling drillDownDependencies function to explore all dependencies
drillDownDependencies(files[file]);
//Adding the current file after exiting from recursion, if it's not already included
if (filesInDependantOrder.indexOf(file) < 0) {
filesInDependantOrder.push(file);
}
}
function drillDownDependencies(root)
{
//Looping through all dependencies of the current file
for (var i = 0; i < root["dep"].length; i++)
{
//Recursively exploring dependencies of each dependency
drillDownDependencies(files[root["dep"][i]]);
//If the dependency has no further dependencies, add it to the list
if (filesInDependantOrder.indexOf(root["dep"][i]) < 0)
{
filesInDependantOrder.push(root["dep"][i]);
}
}
}
console.log(filesInDependantOrder);
The question at hand is: Is my solution foolproof? Could it potentially fail by placing a file before its dependency file? I have considered various scenarios but welcome any insights.
--For those suggesting AMD implementations like require.js, please note that it is not suitable for my requirements.--