Book Image

Learning JavaScript Data Structures and Algorithms - Third Edition

Book Image

Learning JavaScript Data Structures and Algorithms - Third Edition

Overview of this book

A data structure is a particular way of organizing data in a computer to utilize resources efficiently. Data structures and algorithms are the base of every solution to any programming problem. With this book, you will learn to write complex and powerful code using the latest ES 2017 features. Learning JavaScript Data Structures and Algorithms begins by covering the basics of JavaScript and introduces you to ECMAScript 2017, before gradually moving on to the most important data structures such as arrays, queues, stacks, and linked lists. You will gain in-depth knowledge of how hash tables and set data structures function as well as how trees and hash maps can be used to search files in an HD or represent a database. This book serves as a route to take you deeper into JavaScript. You’ll also get a greater understanding of why and how graphs, one of the most complex data structures, are largely used in GPS navigation systems in social networks. Toward the end of the book, you’ll discover how all the theories presented in this book can be applied to solve real-world problems while working on your own computer networks and Facebook searches.
Table of Contents (22 chapters)
Title Page
Dedication
Packt Upsell
Contributors
Preface
Index

Creating the Graph class


As usual, we will declare the basic structure of our class:

class Graph {
  constructor(isDirected = false) {
    this.isDirected = isDirected; // {1}
    this.vertices = []; // {2}
    this.adjList = new Dictionary(); // {3}
  }
} 

The Graph constructor can receive a parameter to indicate if the graph is directed or not ({1}), and by default, the graph will not be directed. We will use an array to store the names of all the vertices of the graph ({2}), and we will use a dictionary (implemented in Chapter 8, Dictionaries and Hashes) to store the adjacent list ({3}). The dictionary will use the name of the vertex as a key and the list of adjacent vertices as a value.

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 graph with no vertices), and another method to add edges between the vertices. Let's implement the addVertex method first, as follows:

addVertex(v) {
  if (!this.vertices...