We'll be creating a graph class that supports weights and both directed and undirected types. This will be implemented using an adjacency list. As we move to more advanced concepts, both weights and directed nature of the graphs will come in handy.
An adjacency list is an array A of separate lists. Each element of the array Ai is a list, which contains all the vertices that are adjacent to vertex i. We're defining it using 2 members, nodes and edges.
Let's set up the graph class by defining our class and some methods that we'll use to add nodes and edges to our graph.
We'll initially define the following methods −
- addNode: Adds a node to the graph
- addEdge: Adds an undirected edge to the graph
- addDirectedEdge: Adds a directed edge
Example
class Graph { constructor() { this.edges = {}; this.nodes = []; } addNode(node) { this.nodes.push(node); this.edges[node] = []; } addEdge(node1, node2) { this.edges[node1].push(node2); this.edges[node2].push(node1); } addDirectedEdge(node1, node2) { this.edges[node1].push(node2); } display() { let graph = ""; this.nodes.forEach(node => { graph += node + "->" + this.edges[node].join(", ") + "\n"; }); console.log(graph); } }
You can test these methods and our class using −
Example
let g = new Graph(); g.addNode("A"); g.addNode("B"); g.addNode("C"); g.addNode("D"); g.addNode("E"); g.addEdge("A", "C"); g.addEdge("A", "B"); g.addDirectedEdge("A", "D"); g.addEdge("D", "E"); g.display();
Output
This will give the output −
A->C, B, D B->A C->A D->E E->D