Basic Ideas about Data Structures in JavaScript

Serajur Reza Chowdhury
5 min readMay 8, 2020

--

Data Structures

Data structure is something that stores data while executing a program.

Data structures help us to give understanding of using data while running a program. A strong grasp of data structures will also help you in your day-to-day job as you approach problems.

Stack

Stack is a data structure in which the data enters at last will be removed first. It follow the LIFO principle(Last In First Out).

Stack operations include,

1. Push

2. Pop

3. Peek

Push — Pushing an element to the stack. Takes an element as argument.

Pop — Removes and returns the latest element that is inserted in the stack.

Peek — Returns the latest element that is inserted in the stack.

The Stack Class

The stack class has a constructor holding two attributes. A storage object which will work as a stack and the length of the object.

class Stack{

constructor(){

this.storage= {}

this.length=0;

}

push(value){

this.storage[this.length]=value

this.length++

return this.storage

}

pop(){

if(this.length==0){

return “Stack is empty. Cannot delete any value”

}

this.length — ;

delete this.storage[this.length]

return this.storage

}

peek(){

if(this.length==0){

return “Stack is empty. Cannot return any value”

}

return this.storage[this.length-1]

}

}

const stack= new Stack()

console.log(stack.push(1));

console.log(stack.peek());

console.log(stack.push(2));

console.log(stack.push(3));

console.log(stack.pop());

console.log(stack.push(3));

console.log(“The stack is “,stack.storage)

pop and peek will not work if the object is empty. The latest item is the (this.length-1)th index of the object.

Stack with Built-in Array method

We can use array as a stack. And array has some built-in methods to make array work like a stack.

push() — pushes one or more elements in an array.

pop() — pops an element from the back of an array.

We can use peek by accessing the last element of an array.

var arr= [1,2,3,4]

//push

arr.push(5)

console.log(arr)

//pop

arr.pop()

console.log(arr)

//peek

var elem = arr[arr.length-1]

console.log(arr[arr.length-1])

Queue

Queue works on FIFO(First in First Out Principle). Which means the first data to be inserted will be removed first.

Queue has three operations,

1. Enqueue — Entering data to queue.

2. Dequeue — Removing data from queue.

3. Peek — Retrieving the latest inserted data.

The Queue Class

The queue class has a constructor holding two attributes. A storage array which will work as a queue and the length of the array.

We have used built-in array methods for Queue,

class Queue{

constructor(){

this.storage= []

this.length=0;

}

enqueue(value){

this.storage.push(value)

this.length++

return this.storage

}

dequeue(){

this.storage.shift()

this.length — ;

return this.storage

}

peek(){

if(this.length==0){

return “queue is empty. Cannot return any value”

}

return this.storage[this.length-1]

}

}

const queue= new Queue()

console.log(queue.enqueue(1));

console.log(queue.enqueue(2));

console.log(queue.dequeue());

console.log(queue.enqueue(3));

console.log(queue.peek());

Linked List

Linked List is a way of forming connection to scattered data. Here, the data is scattered here and there in memory, and they connected through linked list.

Linked List is not something built-in. It is a custom data structure, where dynamic array or built-in data-structures cannot be modified in size.

Each linked list have elements name node. Which at least have an element and a reference of the next node.

Every linked list have a head node where the traversing will start.

class Node{

constructor(data, next=null){

this.data=data

this.next=next

}

}

class LinkedList{

constructor(){

this.head=null

}

print(){

var l=[]

for(var node= this.head; node!==null; node=node.next){

l.push(node.data)

}

return l

}

length(){

var l=0

for(var node= this.head; node!==null; node=node.next){

l++

}

return l

}

add(elem){

var node=new Node(elem)

if(this.head===null){

this.head=node

}

else{

for(var n=this.head; n.next!==null; n=n.next){

}

n.next=node

}

}

remove(elem){

var currentNode=this.head

var previousNode=null

if(currentNode.data === elem){

head=currentNode.next

}

else{

while(currentNode.data!==elem){

previousNode=currentNode;

currentNode=currentNode.next

}

previousNode.next=currentNode.next

}

}

indexOf(elem){

var i=-1;

for(var n=this.head; n!==null; n=n.next){

i++;

if(n.data === elem){

return i

}

}

return -1

}

}

const ll=new LinkedList();

ll.add(1)

ll.add(2)

ll.add(3)

ll.add(4)

console.log(ll.length())

console.log(ll.print())

ll.remove(2)

console.log(ll.length())

console.log(ll.print())

console.log(ll.indexOf(2))

Here, we have implemented add, remove, indexOf methods of a linked list.

Hash Table

Hash Table is something that stores data as a key-value pair. It looks like a JavaScript Object.

You can retrieve, insert or remove a value using a key using hash table. We will use these operations here.

class HashTable{

constructor(size){

this.size=size

this.storage= []

}

myHashingFunction(str, n) {

let sum = 0;

for (let i = 0; i < str.length; i++) {

sum += str.charCodeAt(i)*3

}

return sum % n;

}

add(key,value){

const index= this.myHashingFunction(key, this.size)

if(!this.storage[index]){

this.storage[index]=[]

}

this.storage[index].push([key,value])

}

remove(key){

const index= this.myHashingFunction(key, this.size)

let arrayAtIndex= this.storage[index]

if(arrayAtIndex){

for(var i=0; i<arrayAtIndex.length; i++){

let pair= arrayAtIndex[i]

if(pair[0]===key){

delete arrayAtIndex[i]

break

}

}

}

}

get(key){

const index= this.myHashingFunction(key, this.size)

let arrayAtIndex= this.storage[index]

if(arrayAtIndex){

for(var i=0; i<arrayAtIndex.length; i++){

let pair= arrayAtIndex[i]

if(pair[0]===key){

return pair[1]

}

}

}

}

}

const myHT = new HashTable(5);

myHT.add(“a”, 1);

myHT.add(“b”, 2);

myHT.add(“a”, 2);

myHT.add(“c”, 3);

myHT.remove(‘a’);

console.log(myHT.get(‘c’))

console.log(myHT)

Binary Search Tree

Binary Search Tree is a type of tree which holds two child nodes for one node and the left node value will be the lower than the parent node value and the right node value will be higher than the parent node value.

We need to understand some terms about tree,

Root — The top most node of a tree which does not have any parents.

Parent — A node that is the child of at most two nodes.

Child — A node that is the child of a node, it does not necessarily need to have a child.

Leaves — Nodes those do not have child.

A parent should not have more than two children. Also, the left child and the right child value should be less and more than the parent node value. If these criteria never meets it will not be a binary search tree.

class Node {

constructor(value, left = null, right = null) {

this.value = value;

this.left = left;

this.right = right;

}

}

class Tree {

constructor(value) {

this.root = null

}

add(value) {

if (this.root === null) {

this.root = new Node(value);

return;

}

let current = this.root;

while (true) {

if (current.value > value) {

if (current.left) {

current = current.left;

} else {

current.left = new Node(value);

return;

}

}

else {

if (current.right) {

current = current.right;

} else {

current.right = new Node(value);

return;

}

}

}

}

contains(value) {

let current = this.root;

while (current) {

if (value === current.value) {

return true;

}

current = value < current.value ? current.left : current.right;

}

return false;

}

}

const t = new Tree();

t.add(2);

t.add(5);

t.add(3);

console.log(t)

So, there you are. There is some idea about some data structures. Hope you enjoy your next journey about data structures.

--

--

Serajur Reza Chowdhury
Serajur Reza Chowdhury

Written by Serajur Reza Chowdhury

Software Engineer, curious JavaScript programmer, love to share concepts.

No responses yet