spaceDog spaceDog - 1 year ago 62
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.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){

Graph.prototype.hasEdge = function(fromNode, toNode){
for(var key in this.edges){
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
//call back on each nodes
return cb(this.edges[key]);

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

Answer Source

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();

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