Implement a stack with push and pop functions

Definition of a Stack
A stack is a data structure based on the principle LIFO (Last In First Out). A stack is a container to hold nodes and has two operations — push and pop. The push operation is to add nodes into the stack and pop operation is to delete nodes from the stack and returns the top most node.
Time Complexity
Push Pop Peek Empty Size Swap
O(1) O(1) O(1) O(1) O(1) O(1)
Learn more about Big O here

Why use a stack instead of an array?
  1. Most methods on the Array Prototype have a time complexity of O(n). Let’s look at a specific example like splice(). When you splice an array, it has to find the specific index, remove a specified number of elements, then shift all the following elements forward to fill the place of the removed elements. Contrast this with using the stack (object) which has direct look-up of properties and does not have to be kept ‘in-order’.
  2. Arrays take up a block of space because they have to keep their order, where as an object does not.
What are the various Stack operations?
  1. pop — Pulls (removes) the element out of the stack. The location is specified by the pointer
  2. push — Pushes (inserts) the element in the stack. The location is specified by the pointer.
  3. peek — returns the item on the top of the stack, without removing it.
  4. empty — returns true if the stack is empty, false otherwise
  5. swap — the two top most elements of the stack can be swapped

The code


// Creates a stack
var Stack = function() {
    this.count = 0;
    this.storage = {};
}

// Adds a value onto the end of the stack
Stack.prototype.push = function(value) {
    this.storage[this.count] = value;
    this.count++;
}

// Removes and returns the value at the end of the stack
Stack.prototype.pop = function() {
    // Check to see if the stack is empty
    if (this.count === 0) {
        return undefined;
    }

    this.count--;
    var result = this.storage[this.count];
    delete this.storage[this.count];
    return result;
}

// Returns the length of the stack
Stack.prototype.size = function() {
    return this.count;
}