spaceDog spaceDog - 6 months ago 14
Javascript Question

Final step on my Graph Structure - forEachNode callback

I am at my last stop of Graph Structure. So I am supposed to add callback to each Node.
Two things,
1. when I call a.forEachNode(hasEdge()) -> hasEdge not a function.
2. Do you think my code will work?
Please explain if I am doing something right or wrong. THanks

var Graph = function(){
this.nodes = [];
this.edges = {};
};

Graph.prototype.addNode = function(node){
this.nodes.push(node);
this.edges[node] = {};
};

Graph.prototype.contains = function(node){
return this.nodes.indexOf(node) !== -1;
};

Graph.prototype.removeNode = function(node){
for(var key in this.edges){
if(key === node){
delete this.edges[node];
}
}

for(var i = 0; i < this.nodes.length; i++){
if(this.nodes[i] === node){
this.nodes.splice(i,1);
}
}
};

Graph.prototype.hasEdge = function(fromNode, toNode){
for(var key in this.edges){
if(this.edges[fromNode][toNode]){
return true;
} else {
return false;
}
}
};

Graph.prototype.addEdge = function(fromNode, toNode){
this.edges[fromNode][toNode] = true;
this.edges[toNode][fromNode] = true;
};

Graph.prototype.removeEdge = function(fromNode, toNode){
delete this.edges[fromNode][toNode];
delete this.edges[toNode][fromNode];
};

Graph.prototype.forEachNode = function(cb){
//loop through edges object
for(var key in this.edges){
//if keys exist
if(keys){
//call back on each nodes
return cb(this.edges[key]);
}
}
};





var a = new Graph();
a.addNode("puppies");
a.addNode("kittens");
a.addNode("bears");
a.addEdge("puppies", "kittens");
a.addEdge("puppies", "bears");
a.hasEdge("puppies", "bears");
a.hasEdge("kittens", "bears");
a.forEachNode(addEdge());

Answer

Your code looks good, except last part, where you're trying to pass addEdge() or hasEndge().

hasEdge() - is not defined because it is method of instance of Graph. So there should be something like

var g = new Graph();
a.forEachNode(function(node){
  g.addNode(node)
});

It should add each nodes from graph a to new graph g