Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Learning JavaScript Data Structures and Algorithms

You're reading from   Learning JavaScript Data Structures and Algorithms JavaScript Data Structures and algorithms can help you solve complex development problems – learn how by exploring a huge range of JavaScript data types

Arrow left icon
Product type Paperback
Published in Oct 2014
Publisher Packt
ISBN-13 9781783554874
Length 218 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Loiane Avancini Loiane Avancini
Author Profile Icon Loiane Avancini
Loiane Avancini
Arrow right icon
View More author details
Toc

Creating the Graph class


As usual, we are going to declare the skeleton of our class:

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

We are going to use an array to store the names of all the vertices of the graph (line {1}) and we are going to 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 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 are going to 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. Let's implement the addVertex method first:

this.addVertex = function(v){
    vertices.push(v); //{3}
    adjList.set(v, []); //{4}
};

This method receives a vertex v as parameter. We are going to add this vertex...

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €18.99/month. Cancel anytime