Elementary Data Structures with JavaScript - Stacks🚀
Tags: javascript, programming, codequality, webdev
Published: 2021-02-09 19:58:04

Table Of Contents
        * 🤓 [INTRODUCTION](#intro)
        * ❔ [WHY DATA STRUCTURES](#why)
        * 🔖 [CLASSIFICATION](#classification)
        * 💉 [OPERATIONS](#operations)
        * 📚 [STACKS](#stacks)
        * 🛠 [IMPLEMENTATION](#implement)
        * 👩🏻‍💻 [CODE](#code)
        * 🙏 [THANK YOU](#thank-you)


## 🤓 INTRODUCTION <a name="intro"></a>

Welcome, hackers!🚀 As promised in the previous series, we are starting a new series that is dedicated to elementary data structures in computer science. Data structures are an important part of computer science and programming in general. Data structures can provide you a fresh point of view on how to solve the problem, and how to implement an optimal solution for your problem.

If you missed the previous series "Sorting algorithms with JavaScript", I suggest you start from the beginning. Here is a link:

{% link https://dev.to/codespresso/sorting-algorithms-with-javascript-bubble-sort-45je %}


Also, please feel free to connect with me via [Twitter](https://twitter.com/lazar_dev), [Instagram](https://www.instagram.com/codespressoweb/) or [LinkedIn](https://www.linkedin.com/in/lazar-stankovic-44a199177/)


## ❔ WHY DATA STRUCTURES <a name="why"></a>
A data structure is a data organization, management, and storage format that enables efficient access and modification. A data structure is a way to store and organize data so that it can be used efficiently. There are many ways of organizing the data in the memory, for example, a simple array is a collection of memory elements in which data is stored sequentially (one after another).

The data structure is a set of algorithms that we can use in any programming language to structure the data in the memory.


##🔖 CLASSIFICATION <a name="classification"></a>

- Primitive
- Non-primitive

**Primitive** data structures are primitive data types (integer, char, float, double, and pointer are the primitive data structures). Primitive data structures hold a single value.

**Non-primitive** data structures are furtherly classified into:
- Linear data structures
- Non-linear data structures

**Linear data structure** - The data arrangement is in a sequential manner, and it is known as a linear data structure. The data structures used for this purpose are Arrays, Linked Lists, Stacks, and Queues.

**Non-linear** - When one element is connected to the "n" number of elements - examples are trees and graphs.

Data structures can also be classified into:
- Static - The required size is allocated at the compile time
- Dynamic - The required size is allocated at the run time - it's flexible.


##💉 OPERATIONS <a name="operations"></a>
The common operations that can be performed on the data structures are:
- **Searching** 
- **Sorting**
- **Insertions**
- **Updation**
- **Deletion**


##📚 STACKS <a name="stacks"></a>

The stack is a linear data structure. In the stack, we can only access an element that is on the top of the stack (last added element). This is LIFO data structure or "**L**ast-**I**n, **F**irst-**O**ut"

A Stack is a special case of a linear list. We can only add or delete an element from only one end of the list.

The insert operation on a stack is often called PUSH, and the DELETE operation, which does not take an element argument, is often called POP. These names are allusions to physical stacks, such as the spring-loaded stacks of plates used in cafeterias. The order in which plates are popped from the stack is the reverse of the order in which they were pushed onto the stack since only the top plate is accessible.


##🛠 IMPLEMENTATION <a name="implement"></a>
Let's say I am Iron Man 😂 And I have a stack of suits of armor that I can use. Here is how I would add a new suit of armor, delete the suit of armor or check how many of them I have using stack data structure. Let's name it the **StarkStack**!

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/0csoh5pzhj6rue5t7zzc.png)


##👩🏻‍💻 CODE <a name='code'></a>
```javascript
class StarkStack {
    constructor(){
        this.data = [];
        this.top = 0;
    }
    push(element) { //adds a suit on top of the stack
      this.data[this.top] = element;
      this.top = this.top + 1;
    }
   length() {
      return this.data.length;
   }
   peek() { //Get the Top suit of the Stack
      return this.data[this.top-1];
   }
   isEmpty() {
     return this.top === 0;
   }
   pop() { //read and remove an suit from the top of the stack
    if( this.isEmpty() === false ) { //remove only if stack is not empty
       this.top = this.top -1;
       return this.data.pop(); //remove the last suit
     }
   }
   print() {
      var top = this.top - 1; 
      while(top >= 0) {
          console.log(`Stack of suits at ${top+1}: ${this.data[top]}`);
          top--;
       }
    }
    reverseMyStack() {
       this.reverse(this.top - 1 );
    }
    reverse(index) {
       if(index != 0) {
          this.reverse(index-1);
       }
       console.log(`Reversed stack of suits at ${index+1}: ${this.data[index]}`);
    }
}

var stack = new StarkStack();
stack.push("Space Armor MK1");
stack.push("Iron Man Armor MK VII");
stack.push("Iron Man Armor MK VI");
stack.push("Hydro Armor");
stack.push("Mark IX");
stack.push("Mark X");
stack.push("Mark Xi");
stack.print();
stack.reverseMyStack();
console.log(`The suit on the top: ${stack.peek()}`);
console.log(`Number of suits in the stack: ${stack.length()}`);
/*
OUTPUT
Stack of suits at 7: Mark Xi
Stack of suits at 6: Mark X
Stack of suits at 5: Mark IX
Stack of suits at 4: Hydro Armor
Stack of suits at 3: Iron Man Armor MK VI
Stack of suits at 2: Iron Man Armor MK VII
Stack of suits at 1: Space Armor MK1
Reversed stack of suits at 1: Space Armor MK1
Reversed stack of suits at 2: Iron Man Armor MK VII
Reversed stack of suits at 3: Iron Man Armor MK VI
Reversed stack of suits at 4: Hydro Armor
Reversed stack of suits at 5: Mark IX
Reversed stack of suits at 6: Mark X
Reversed stack of suits at 7: Mark Xi
The suit on the top: Mark Xi
Number of suits in the stack: 7
*/
```
# 🙏 THANK YOU FOR READING!<a name="thank-you"></a>
References:
School notes...
School books...

Please leave a comment, tell me about you, about your work, comment your thoughts, connect with me! 

☕ SUPPORT ME AND KEEP ME FOCUSED!
<a href='https://ko-fi.com/Z8Z33D1HJ' target='_blank'><img height='36' style='border:0px;height:36px;' src='https://cdn.ko-fi.com/cdn/kofi4.png?v=2' border='0' alt='Buy Me a Coffee at ko-fi.com' /></a>

Have a nice time hacking! 😊