Search code examples
javascriptclassstack

Overflow & Underflow


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.

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() {
        
    }
}

Solution

  • 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];
      }
    }