Skip to content

Instantly share code, notes, and snippets.

@darshna09
Created July 10, 2021 09:55
Show Gist options
  • Save darshna09/e0c3c327c8ef12ca8fbef9839a0fbee4 to your computer and use it in GitHub Desktop.
Save darshna09/e0c3c327c8ef12ca8fbef9839a0fbee4 to your computer and use it in GitHub Desktop.
class Stack {
constructor() {
this.list = [];
}
// Peek the top element.
peek() {
this.list.length ? console.log(this.list[this.list.length - 1]) : console.log('The stack is empty.');
return this.list.length;
}
// Push the element.
push(value) {
this.list.push(value);
console.log(this.list);
return this.list.length;
}
// Pop the last element.
pop() {
this.list.length ? console.log(this.list.pop()): console.log('The stack is empty.');
return this.length;
}
}
const myStack = new Stack();
myStack.push('Udemy'); // [ 'Udemy' ]
myStack.push('Google'); // [ 'Udemy', 'Google' ]
myStack.push('Discord'); // [ 'Udemy', 'Google', 'Discord' ]
myStack.peek(); // Discord
myStack.pop(); // Discord
myStack.pop(); // Google
myStack.pop(); // Udemy
myStack.pop(); // The stack is empty.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment