Arranging File Dependencies in the Correct Sequence

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.--

Answer №1

As long as there are no circular dependencies, your solution should work.

Just so you know, this process is known as topological sorting. The Wikipedia page provides algorithms that can effectively perform the sort and identify circular dependencies:

L ← Empty list for sorted elements
S ← Set of nodes without incoming edges
while S is not empty:
    take node n from S
    add n to end of L
    for each node m with edge e from n to m:
        remove edge e 
        if m has no other incoming edges:
            insert m into S
if graph still has edges:
    return error (graph contains a cycle)
else:
    return L (sorted order)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Vue: Initializing data as a string with hyperlink

I am working with an array of objects called boxData within my initial data. Is it possible to transform the word "here" into a hyperlink that I can later reference in relation to boxData? data() { return { boxData: [ { ...

Node JS fails to return body content in POST request

Exploring Node JS for the first time and attempting to post data to a specific URL and retrieve it. Using Postman for this task, but encountering an issue where the response data is coming back as undefined despite receiving a 200 status code. Even after ...

What is the best way to format or delete text enclosed in quotation marks within an anchor tag using CSS or JavaScript?

I have encountered an issue with a dynamically generated login form. When I select the 'Forgot Password' option, a new 'Back to Login' message appears along with a separating '|' line. Removing this line is proving challenging ...

The steps to dynamically change the mute setting of an Audio element in the DOM

I'm looking for assistance with updating the DOM audio in real time. My goal is to allow users to mute and unmute the audio based on their preferences. The recorded audio file is stored in the public folder. Initially, the audio works fine when loa ...

Reached the maximum number of iterations for Angular 10 $digest() function

Currently, I am following a MEAN stack tutorial on Thinkster and encountering an issue with my Angular factory service. Angular.js:11598 Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting! Watchers fired in the last 5 iterations: [] H ...

The function of hasClass within an if statement appears to be malfunctioning

I'm struggling to figure out why my .hasClass function is not functioning correctly. I've implemented the Quick Search jQuery plugin, and below is the code I am using: <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.mi ...

What are the most effective techniques for managing headers, footers, and reusable templates in Node.js/Express views?

Currently, I've got my development environment configured with Node.JS / Express / Pug and I'm in the process of grasping the usage of views & routes. However, I seem to be struggling when it comes to embedding a "reusable" navigation bar and foo ...

Guide to enhancing jQuery tooltip plugin with ajax support - integrating live functionality

I am currently using a jQuery plugin from However, I am facing an issue where the plugin does not work properly when using Ajax. I would like to modify or add a function live() to address this problem. Here is the complete code: http://pastebin.com/up6KY ...

Creating a hierarchical data structure in PHP to represent a file tree and then displaying it using Vue

I am currently working on creating a file tree array using PHP, based on the data structure outlined in var treeData from Tree View - Vue.js (visible in javascript tab). var treeData = [ { name: 'My Tree', children: [ { name: &a ...

Instructions on how to retrieve a JSON file from an external source

I'm experiencing difficulties in downloading a json file from an external URL using nodejs. The issue arises when the downloaded file (dumpFile.json) is created empty. var file = fs.createWriteStream("download/dumpFile.json"); let URL = 'http:// ...

Ways to resolve the npm installation issue "npm ERR! code 1"

Upon attempting to install this project, I encountered an issue after running npm install: npm ERR! code 1 npm ERR! path C:\xampp\htdocs\sss\node_modules\deasync npm ERR! command failed npm ERR! command C:\Windows&bs ...

Tips for Modifying CSS Design for Unhovered Elements

HTML <ul id="menu"> <li><a href="#">Home</a></li> <li><a href="#">Categories</a> <ul> <li><a href="#">1</a></li> < ...

Display different text on a webpage based on login status

I am looking to display certain buttons on a webpage based on the user's login status in an MVC view page. To achieve this, I am using an Ajax function to check the user's login status and then show or hide the button accordingly. However, sinc ...

What is a memory-saving method to clear an object in JavaScript?

I am looking for a way to use the same object repeatedly in JavaScript by emptying it after its purpose is served, without creating a new object each time. In arrays, I usually do arr.length=0 to clear an array instead of assigning it to a new memory locat ...

Mastering the perfect synchronization of useState and useEffect

I'm struggling with comparing the values of two inputs, specifically for a password and confirm password input in a form. While using onChange in React useState to render the DOM is straightforward, I know that I should be utilizing useEffect as well ...

Error loading Azure Active Directory web form: Server returned a 401 status code for the requested resource

I recently made changes to my web site (incorporating a web form and entity framework) to use AAD connection, following the guidance in this insightful blog post. However, I am encountering an issue where scripts and css files are not loading properly. Th ...

Utilize jQuery to locate a specific value within a collapsible Bootstrap 4 table

Is it possible to use a Bootstrap 4 table inside a collapse? I need to search for a specific value in the table and if the value is found, I want to open the collapse and display the row containing that value. <div id="collapseStudents" class="collapse ...

Expressing the relationship between API endpoints in a nested structure

I'm currently working on a REST API using expressjs. There are two api endpoints that I have defined: router.get('/probe/:id', function() {}); router.get('/:id', function() {}); However, I am facing an issue where calling the fir ...

Understanding how to decode querystring parameters within a Django view

In the application I'm working on, there is a search form that utilizes a jQuery autocomplete plugin. This plugin processes the querystring and sends back the suggested item using encodeURI(q). For example, an item like Johnny's sports displays ...

What is the best way to retrieve information from a data set?

After borrowing some basic HTML, CSS, and JavaScript code from CodePen, I ran into an issue while attempting to convert it to React. The error message says that it cannot read properties of null (specifically 'dataset'). Here is the JavaScript c ...