DS#1 STACK

Stack Object Implementation

by bhupendra negi

HTML

<script src="https://rawgit.com/eu81273/jsfiddle-console/master/console.js"></script>

JavaScript

function Stack(capacity) {
  this._capacity = capacity || Infinity;
  this._storage = {};
  this._count = 0;
}

// push 
Stack.prototype.push = function(val) {

  if (this._count < this._capacity) {
    this._storage[this._count++] = val;
    return this._count;
  } else {
    return "Max capacity reached no more space to add "
  }

}

// pop
Stack.prototype.pop = function() {
  if (this._count > 0) {
    var val = this._storage[this._count - 1];
    delete this._storage[this._count - 1] ? this._count-- : this._count;
    return val;
  } else {
    this._count = 0;
    return "Stack empty now , push anything to delete";
  }
}

// peek
Stack.prototype.peek = function() {
  return this._storage[this._count - 1];
}

// count
Stack.prototype.count = function() {
  return this._count;
}

// Contains : O(n);
Stack.prototype.contains = function(val) {
  var contains = false;
  for (var key in this._storage) {
    if (val === this._storage[key]) {
      contains = true;
      break;
    }
  }
  return contains;
}

// Untill
Stack.prototype.untill = function(val) {
  var counter = this._count - 1,
    found = false;    
  for (var i = counter; i >= 0; i--) {
    if (this._storage[i] === val) {
      found = true;      
      break;
    }
  }
  if (found) {
    return (counter - i)
  } else return "element not found !!"

}

// Debugging .....

var myStack = new Stack(4);
console.log(myStack.push(1));
console.log(myStack.push(2));
console.log(myStack.push(3));
console.log(myStack.push(4));
console.log(myStack.push(5));
console.info("Untill...");
console.log(myStack.untill(1));
console.info("Contains...")
console.log(myStack.contains(41));
console.info("Removing...")
console.log(myStack.pop());
console.log("Peek...");
console.log(myStack.peek());
console.info("Removing...")
console.log(myStack.pop());
console.log(myStack.peek());
console.log(myStack.pop());
console.log(myStack.peek());
console.log(myStack.pop());
console.log(myStack.peek());
console.log(myStack.pop());