Here are the requirements:
To demonstrate your understanding of the Graphs data structure, you need to complete the
addEdge()
method to establish bidirectional edges between two vertices.Make sure to validate that each argument is an instance of the
Vertex
class.An example
Graph
object namedfriendNetwork
is provided for testing the functionality of theaddEdge()
method as you implement it.
This is my code snippet:
const Edge = require('./Edge.js');
const Vertex = require('./Vertex.js');
class Graph {
constructor() {
this.vertices = [];
}
addVertex(data) {
const newVertex = new Vertex(data);
this.vertices.push(newVertex);
return newVertex;
}
addEdge(vertexOne, vertexTwo) {
if (!(vertexOne instanceof Vertex) || !(vertexTwo instanceof Vertex)) {
throw new Error('Edge start and end must both be Vertex');
}
const newEdge = new Edge(vertexOne, vertexTwo);
vertexOne.addEdge(newEdge);
vertexTwo.addEdge(newEdge);
}
print() {
this.vertices.forEach(vertex => vertex.print());
}
}
const friendNetwork = new Graph();
const friendSara = friendNetwork.addVertex('Sara');
const friendMeera = friendNetwork.addVertex('Meera');
friendNetwork.addEdge(friendSara, friendMeera);
friendNetwork.print();
module.exports = Graph;
I encountered an error message:
/home/ccuser/workspace/assessment-aed01d489e69459a85cbdc42c2a13067/Vertex.js:13
throw new Error('Edge start and end must both be Vertex');
^
Error: Edge start and end must both be Vertex
at Vertex.addEdge (/home/ccuser/workspace/assessment-aed01d489e69459a85cbdc42c2a13067/Vertex.js:13:13)
at Graph.addEdge (/home/ccuser/workspace/assessment-aed01d489e69459a85cbdc42c2a13067/Graph.js:22:15)
at Object.<anonymous> (/home/ccuser/workspace/assessment-aed01d489e69459a85cbdc42c2a13067/Graph.js:34:15)
at Module._compile (internal/modules/cjs/loader.js:1085:14)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
at Module.load (internal/modules/cjs/loader.js:950:32)
at Function.Module._load (internal/modules/cjs/loader.js:790:12)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:75:12)
at internal/main/run_main_module.js:17:47
I attempted to troubleshoot the add edge method hoping for a successful outcome. I even tried changing the class to Vertex instead of Graph, but unfortunately, my solution was not accepted.