Creating the Graph class

As usual, we will declare the skeleton of our class:

function Graph() { 
  var vertices = []; //{1} 
  var adjList = new Dictionary(); //{2} 
} 

We will use an array to store the names of all the vertices of the graph (line {1}), and we will use a dictionary (implemented in Chapter 7 , Dictionaries and Hashes) to store the adjacent list (line {2}). The dictionary will use the name of the vertex as a key and the list of adjacent vertices as a value. Both the vertices array and the adjList dictionary are private attributes of our Graph class.

Next, we will implement two methods: one to add a new vertex to the graph (because when we instantiate the graph, it will create an empty one) and another method to add edges between the vertices. ...

Get Learning JavaScript Data Structures and Algorithms - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.