Skip to content

Commit

Permalink
Faster implementation for dropping nodes in big graphs.
Browse files Browse the repository at this point in the history
  • Loading branch information
tjdett committed Nov 6, 2012
1 parent 28e210b commit acb7177
Showing 1 changed file with 35 additions and 28 deletions.
63 changes: 35 additions & 28 deletions src/core/graph.js
Original file line number Diff line number Diff line change
Expand Up @@ -184,41 +184,48 @@ function Graph() {
*/
function dropNode(v) {
var a = (v instanceof Array ? v : [v]) || [];
var nodesIdsToRemove = {};

// Create hash to make lookups faster
a.forEach(function(id) {
if (self.nodesIndex[id]) {
var index = null;
self.nodes.some(function(n, i) {
if (n['id'] == id) {
index = i;
return true;
}
return false;
});

index != null && self.nodes.splice(index, 1);
delete self.nodesIndex[id];

var edgesToRemove = [];
self.edges = self.edges.filter(function(e) {
if (e['source']['id'] == id) {
delete self.edgesIndex[e['id']];
e['target']['degree']--;
e['target']['inDegree']--;
return false;
}else if (e['target']['id'] == id) {
delete self.edgesIndex[e['id']];
e['source']['degree']--;
e['source']['outDegree']--;
return false;
}
return true;
});
}else {
nodesIdsToRemove[id] = true;
} else {
sigma.log('Node "' + id + '" does not exist.');
}
});

var indexesToRemove = [];
self.nodes.forEach(function(n, i) {
if (n['id'] in nodesIdsToRemove) {
// Add to front, so we have a reverse-sorted list
indexesToRemove.unshift(i);
// No edges means we are done
if (n['degree'] == 0) {
delete nodesIdsToRemove[n['id']];
}
}
});

indexesToRemove.forEach(function(index) {
self.nodes.splice(index, 1);
});

self.edges = self.edges.filter(function(e) {
if (e['source']['id'] in nodesIdsToRemove) {
delete self.edgesIndex[e['id']];
e['target']['degree']--;
e['target']['inDegree']--;
return false;
}else if (e['target']['id'] in nodesIdsToRemove) {
delete self.edgesIndex[e['id']];
e['source']['degree']--;
e['source']['outDegree']--;
return false;
}
return true;
});

return self;
};

Expand Down

0 comments on commit acb7177

Please sign in to comment.