class Stack {
constructor () {
this.stack = []
this.top = 0
}
push (newValue) {
this.stack.push(newValue)
this.top += 1
}
pop () {
if (this.top !== 0) {
this.top -= 1
return this.stack.pop()
}
throw new Error('Stack Underflow')
}
get length () {
return this.top
}
get isEmpty () {
return this.top === 0
}
get last () {
if (this.top !== 0) {
return this.stack[this.stack.length - 1]
}
return null
}
static isStack (el) {
return el instanceof Stack
}
}
const newStack = new Stack()
console.log('Is it a Stack?,', Stack.isStack(newStack))
console.log('Is stack empty? ', newStack.isEmpty)
newStack.push('Hello world')
newStack.push(42)
newStack.push({ a: 6, b: 7 })
console.log('The length of stack is ', newStack.length)
console.log('Is stack empty? ', newStack.isEmpty)
console.log('Give me the last one ', newStack.last)
console.log('Pop the latest ', newStack.pop())
console.log('Pop the latest ', newStack.pop())
console.log('Pop the latest ', newStack.pop())
console.log('Is stack empty? ', newStack.isEmpty)