DEV Community

Ivy-Walobwa
Ivy-Walobwa

Posted on

Stack: Array as Storage

Before writing this, I had a serious debate with myself. Is there a need to implement your own stack using arrays in JavaScript, when the the language itself provides methods, pop() and push(), which are needed in a typical stack???

For the sake of understanding stacks better, I ended up implementing my own, assuming that my stack grows dynamically.

Implementation

1.Create a stack class

class Stack {
    constructor() {
        this.items = [];
        this.size = -1;
    }
//add methods
}
Enter fullscreen mode Exit fullscreen mode

In our stack class, we declare an array to implement a stack and set the size to -1 (empty).

2.Add methods to stack class to perform push, pop, peek.

push item to stack

push(data) {
        //if an item is provided
        if (data) {
            //add item to array
            this.items.push(data);
            //increase size
            this.size++;
        }
        return;        
    }
Enter fullscreen mode Exit fullscreen mode

Here, an item is added to top of stack.

pop item in stack
The top item in stack is removed and returned. If list is empty Underflow is returned.

pop() {
    //if empty
    if (this.size === -1) {
      return "UnderFlow";
    } else {
        this.size--;
        //return top item in stack
      return this.items.pop();
    }
  }
Enter fullscreen mode Exit fullscreen mode

peek
Returns top element but does not remove it from stack

 peek() {
    //if empty
    if (this.size === -1) {
      return "Empty stack";
    }
    //return top item in stack
    return this.items[this.size];
  }

Enter fullscreen mode Exit fullscreen mode

Example Test Code

let stack = new Stack();
stack.push(3);
stack.push(5);
stack.push(7);
console.log(stack.pop());//7
console.log(stack.peek());//5
console.log(stack)//[3, 5]
Enter fullscreen mode Exit fullscreen mode

Next, I'll be applying my stack knowledge in creating a postfix calculator 😉 .
Happy coding.

Top comments (0)