While attempting to create a Graph and incorporating one method at a time, I encountered an issue. Specifically, after calling a.contains("cats"), I received the error '//TypeError: Cannot read property 'length' of undefined'. Could this be related to this.nodes.splice(i,1) after removing all values?
var Graph = function(){
this.nodes = [];
this.edges = {};
};
Graph.prototype.addNode = function(node){
this.nodes.push(node);
this.edges[node] = {};
};
Graph.prototype.contains = function(node){
for(var i = 0; i < this.nodes[i].length; i++){
if(this.nodes[i] === node){
return true;
} else {
return false;
}
}
};
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);
}
}
};
var a = new Graph();
a.addNode("cats");
a.addNode("dogs");
a.contains("cats");
a.removeNode("dogs");
a.contains("cats");
a.removeNode("cats");
a.contains("cats"); //TypeError: Cannot read property 'length' of undefined