Home > Software engineering >  Overflow & Underflow
Overflow & Underflow

Time:01-30

I am trying to figure out the solution but I can't find it... I need a function that throws an error when Maximum call stack is reached and throws an error when Minimum call stack is reached... Kindly Help me with this problem ASAP!

class Stack {
constructor() {
    this.items = [];`Please Help me with this...`
}
push(item) {
    this.items.push(item)
}
pop() {
    const popped = this.items.pop();
    if (this.items == null) {
        throw new Error("Underflow");
    }
    return popped;
}
isEmpty() {
    
}
peek() {
    
}

}

CodePudding user response:

How about modifying your functions?

push and pop should throw an error if Number.MAX_SAFE_INTEGER or <= 0 is reached.

class Stack {
  constructor() {
    this.items = [];
  }
  push(item) {
    if (this.items.length >= Number.MAX_SAFE_INTEGER) {
      throw new Error("Maximum call stack reached");
    }
    this.items.push(item)
  }
  pop() {
    if (this.items.length <= 0) {
      throw new Error("Minimum call stack reached");
    }
    return this.items.pop();
  }
  isEmpty() {
    return this.items.length === 0;
  }
  peek() {
    return this.items[this.items.length - 1];
  }
}
  • Related