Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ghanshyam-K-Dobariya/3f8c53965402a63e2a6594080b5b8cde to your computer and use it in GitHub Desktop.
Save Ghanshyam-K-Dobariya/3f8c53965402a63e2a6594080b5b8cde to your computer and use it in GitHub Desktop.
Find job execution order when one job is dependent on another job(s)
const inputX = {
1: [2],
2: [3],
3: [4],
4: [6, 1],
};
const inputY = {
1: [2, 3],
2: [4, 5],
};
const Z = {
1: [2, 6],
3: [4, 6, 5],
5: [4],
};
/* converted above inputs to below type of JSON */
const hashmapX = {
1: {
2: 2,
},
2: {
3: 3,
},
3: {
4: 4,
},
4: {
1: 1,
},
6: {},
};
const hashmapY = {
1: {
2: 2,
3: 3,
},
2: {
4: 4,
5: 5,
},
3: {},
4: {},
5: {},
};
const hashmapZ = {
1: {
2: 2,
6: 6,
},
2: {},
3: {
4: 4,
6: 6,
5: 5,
},
4: {},
5: {
4: 4,
},
6: {},
};
const getJobOrders = (jobDepenencyHashmap) => {
const jobOrder = [];
const jobIds = Object.keys(jobDepenencyHashmap);
const iterrateHashmap = (idToFind = '') => {
for(const jobId in jobDepenencyHashmap) {
if (jobDepenencyHashmap[jobId]) {
if (jobDepenencyHashmap[jobId][idToFind]) {
delete jobDepenencyHashmap[jobId][idToFind];
}
if (Object.keys(jobDepenencyHashmap[jobId]).length === 0) {
delete jobDepenencyHashmap[jobId];
jobOrder.push(jobId);
iterrateHashmap(jobId);
}
}
}
}
iterrateHashmap(jobDepenencyHashmap);
const response = jobOrder.length === jobIds.length ? jobOrder : 'Circular Dependency';
return response;
};
const testCases = [hashmapX, hashmapY, hashmapZ];
console.log(testCases.map(getJobOrders));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment