Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Code cleanup

  • Loading branch information...
commit 85677c956f7ff33ebdc930e537567c81c0cc90a4 1 parent 7942608
@robrighter authored
Showing with 23 additions and 25 deletions.
  1. +23 −25 topological-sort.js
View
48 topological-sort.js
@@ -1,27 +1,26 @@
-function topologicalSort(graph){
+function topologicalSort(graph) {
var numberOfNodes = graph.length;
var processed = [];
var unprocessed = [];
var queue = [];
- populateIndegreesAndUnprocessed();
- processList();
- return processed;
+
+ function iterate(arr, callback){
+ var i;
+ for(i=0;i<arr.length;i++){
+ callback(arr[i], i);
+ }
+ }
function processList(){
- var toBeRemoved = [];
for(var i=0; i<unprocessed.length; i++){
var nodeid = unprocessed[i];
if(graph[nodeid].indegrees === 0){
queue.push(nodeid);
- console.log('About to remove edge ' + i + ' from the graph.');
unprocessed.splice(i, 1); //Remove this node, its all done.
i--;//decrement i since we just removed that index from the iterated list;
}
}
- console.log(unprocessed);
- console.log('\n\n');
-
processStartingPoint(queue.shift());
if(processed.length<numberOfNodes){
processList();
@@ -29,40 +28,39 @@ function topologicalSort(graph){
}
- function processStartingPoint(i){
- if(i == undefined){
+ function processStartingPoint(nodeId){
+ if(nodeId == undefined){
throw "You have a cycle!!";
}
- for( var t=0; t<graph[i].edges.length; t++){
- var e = graph[i].edges[t];
+ iterate(graph[nodeId].edges, function(e){
graph[e].indegrees--;
- };
- processed.push(i);
+ });
+ processed.push(nodeId);
}
function populateIndegreesAndUnprocessed(){
- for(var i=0; i<graph.length; i++){
- unprocessed.push(i);
- if(!graph[i].hasOwnProperty('indegrees')){
- graph[i].indegrees = 0
+ iterate(graph, function(node, nodeId){
+ unprocessed.push(nodeId);
+ if(!node.hasOwnProperty('indegrees')){
+ node.indegrees = 0
}
- for( var t=0; t<graph[i].edges.length; t++){
- var e = graph[i].edges[t];
+ iterate(node.edges, function(e){
if(!graph[e].hasOwnProperty('indegrees')){
graph[e].indegrees = 1
}
else{
graph[e].indegrees = graph[e].indegrees + 1;
}
- }
- }
+ });
+ });
}
-
+ populateIndegreesAndUnprocessed();
+ processList();
+ return processed;
}
-
if(module){
module.exports.topologicalSort = topologicalSort;
}
Please sign in to comment.
Something went wrong with that request. Please try again.