peek operation in stack using javascript

How can I get the first element from my stack here is my code

var stack = [];
stack.push(id1);
stack.push(id2);

I know there is something like peek in java. Is there any similar method in JS using which i can get the topmost element?

Answers:

Answer

To check the topmost element unfortunately you must explicitly index it

var top = stack[stack.length-1];

the syntax stack[-1] (that would work in Python) doesn't work: negative indexes are valid only as parameters to slice call.

// The same as stack[stack.length-1], just slower and NOT idiomatic
var top = stack.slice(-1)[0];

To extract an element there is however pop:

// Add two top-most elements of the stack
var a = stack.pop();
var b = stack.pop();
stack.push(a + b);
Answer

var stack = [];
stack.push("id1");
stack.push("id2");
console.log(stack[stack.length-1]); // the top element
console.log(stack.length); //size

Answer

If you just need one edge of your stack (head or tail is not matter) use it reversed:

I mean :

peek() become array[0],
unshift(v) become push()
shift() become pop()

some code:

class Stack{
  constructor(... args ){
    this.store = [... args.reverse()];
  }
  peek(){
    return this.store[0];
  }
  push(value){
    return this.store.unshift(value);
  }
  pop(){
   return this.store.shift();
  }
}

const stack = new Stack(1,2,3);
stack.push(4);
console.log(stack.peek());
stack.pop();
console.log(stack.peek())

or shorter

function Stack(...rest){
  var store = [... rest.reverse() ];
  return {
    push:(v)=> store.unshift(v) ,
    pop : _ => store.shift(),
    peek: _ => store[0]
    }
  }
  
var stack = Stack(1,2,3);
console.log(stack.peek());
stack.push(4);
console.log(stack.peek());
stack.pop(), stack.pop();
console.log(stack.peek());

Answer

        var stack = [];
        stack.push("id1");
        stack.push("id2");
        var topObj = stack[0]
       console.log(topObj)
 

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.