JavaScript ES6/ES2015 Implementation of a Stack.

Definition

A stack is a data structure in which items are retrieved in the reverse order that they were added. If you add an item, this item will also be the first one to be removed. This is sometimes abbreviated as LIFO – Last In First Out.

This stack implementation will have 3 methods:

  • push: Add a new item on top of the stack
  • pop: Remove the item on top of the stack
  • peek: Get the value of the item on top of the stack

Array Implementation

Let’s start with using an Array as the underlying structure for our Stack. Since the Array in JavaScript already behaves like a stack, the implementation is trivial.

class Stack {
constructor() {
this.items = [];
this.count = 0;
}

getLength() {
return this.count;
}

push(item) {
this.items.push(item);
this.count = this.count + 1;
}

pop() {
if(this.count > 0) {
this.count = this.count - 1;
}

return this.items.pop();
}

peek() {
return this.items.slice(-1)[0];
}
}

See it in action here;

LinkedList Implementation

Another way of implementing the stack is by using a LinkedList. I am going to be using my LinkedList implementation for this.

Although not as trivial as with using an Array, it is pretty straightforward with the LinkedList:

  • Push adds the element at the beginning of the list
  • Pop returns the first element of the list and removes it at the same time.
class Stack {
constructor() {
this.list = new LinkedList();
}

push(item) {
this.list.addFirst(item);
}

pop() {
if(!this.list.length) {
return;
};

let val = this.list.head.data;
this.list.removeFirst();

return val;
}

peek() {
if(!this.list.head) { return; }
return this.list.head.data;
}

get length() {
return this.list.length;
}
}

See it in Action here;