Skip to content

Instantly share code, notes, and snippets.

@RubyTuesdayDONO
Forked from six8/gist:1732686
Last active March 11, 2022 18:11
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save RubyTuesdayDONO/5006455 to your computer and use it in GitHub Desktop.
Save RubyTuesdayDONO/5006455 to your computer and use it in GitHub Desktop.
logic revisions to pass test case
// Dependency resolution, adapted from https://gist.github.com/1232505/f16308bc14966c8d003c2686b1c258ec41303c1f
function resolve(graph) {
var sorted = [], // sorted list of IDs ( returned value )
visited = {}; // hash: id of already visited node => true
// 2. topological sort
Object.keys(graph).forEach(function visit(name, ancestors) {
if (!Array.isArray(ancestors)) ancestors = [];
ancestors.push(name);
visited[name] = true;
graph[name].forEach(function(dep) {
if (ancestors.indexOf(dep) >= 0) // if already in ancestors, a closed chain exists.
throw new Error('Circular dependency "' + dep + '" is required by "' + name + '": ' + ancestors.join(' -> '));
// if already exists, do nothing
if (visited[dep]) return;
visit(dep, ancestors.slice(0)); // recursive call
});
if(sorted.indexOf(name)<0) sorted.push(name);
});
return sorted;
}
var subscribers = {
html: ['foo'],
value: ['options', 'html'],
foo: ['options'],
bar: ['options', 'html'],
options: [],
css: ['value'],
elements: ['css', 'html', 'options']
};
/*
Expected:
options
foo
html
value
bar
css
elements
*/
var execution_order = resolve(subscribers);
// var execution_order = resolve(subscribers);
execution_order.forEach(function(name) {
console.log(name);
});
@Amitkad
Copy link

Amitkad commented May 22, 2016

works great ! i got here through the post you have upgraded.. and the other one didn't work. well done mate !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment