Similar to tree data structures, a graph is a non-linear data structure. Graphs are made up of nodes and edges. You may also see nodes referred to as vertices and edges referred to as lines. A real life application of a graph could be storing users of a social media network, where the node contains information about the user and the edges show their connections to other users.
When implementing this graph we are going to be using an adjacency list. The basics of the list is that it is going to be a map where each value represents a node and each value will be an array containing all of the nodes edges.
To create our graph we are going to need two basic functions. One to add new nodes, and another to add edges.
For our node function we are going to simply add in our data for our node and associate that node with an empty array which will later store it's edges.
When adding our edges we pass in the two nodes we want to connect with an edge. We use the map's get method to find the node and add the other node to it's list. We need to do this for the other node as well because graphs are non-directional.
A third method that we can implement to help us better view our graph is print. Using ES6 syntax we use a for of loop to print every key value pair in our list.
Voila! After creating some sample data and running it everything seems to be working.
Thanks for reading this far. Next week we'll look at how to search graphs. The code for this post can be found here.
Top comments (0)