Data Structures & Algorithms(Stacks)

Stack in javaScript examples

by manoj_antony32

JavaScript

var arr =[];
var name = "manoj";
var revName = '';
for(var i=0;i < name.length; i++){
	arr.push(name[i]);
}
for(var i=0;i < name.length; i++){
	revName += arr.pop();
}

/* Another stack example */

var stack = function(){
	this.count = 0;
  this.storage = {};
  
  this.push = function(value){
  	this.storage[this.count] = value;
    this.count++;
  }
  
  this.pop = function(){
   if(this.count == 0){
   		return undefined;
   }
   this.count--;
   var result = this.storage[this.count];
   delete this.storage[this.count];
   return result;
  }
  this.peek = function(){
   //this.count--;
   var result = this.storage[this.count-1];
   return result;  
  }
  this.size = function(){
  	return this.count;
  }
}

var testStack = new stack();
testStack.push(2);
testStack.push(1);
console.log(testStack)
testStack.pop();
console.log(testStack)
testStack.peek();
console.log(testStack)