Home > Back-end >  Stuck in a JavaScript stack algorithm
Stuck in a JavaScript stack algorithm

Time:01-24

The isEmpty() algorithm is asking me to return true when the stack contains no values and to return false when stack contains one or more values. it also asks to complete this without modifying the stack

i can only use 3 methods

  • .pop() which pops the top value of the stack

  • .push() which pushes a value on to the stack

  • .peek() which shows me the top value of the stack without modifying the stack

i tried doing the algorithm this way but it only completed the last two requirements which where to return false when the stack contains one or more values and to not modify the stack but it wont return true when the stack contains no values enter image description here

function isEmpty(stack) {
if(stack!==''){
  return false
}else if(stack===''){
  return true
}
}

CodePudding user response:

function isEmpty(stack) {
  if (stack.peek() === undefined) {
    return true;
  } else {
    return false;
  }
}

OR

function isEmpty(stack) {
  return stack.peek() === undefined;
}

CodePudding user response:

Here is one way you could use the peek() method to solve this problem:

function isEmpty(stack) {
if(stack.peek() === undefined){
    return true;
}else{
    return false;
}
}

CodePudding user response:

just check if the peek() function is equalto undefined

function isEmpty(){
return peek() == undefined;
}
  • Related