Skip to content

Instantly share code, notes, and snippets.

@sabique
Created October 12, 2020 20:16
Show Gist options
  • Save sabique/02a2f914503dbf0bc31f80ff531c18c0 to your computer and use it in GitHub Desktop.
Save sabique/02a2f914503dbf0bc31f80ff531c18c0 to your computer and use it in GitHub Desktop.
/** Class representing a Stack. */
class Stack {
constructor() {
this._storage = {};
this._length = 0;
}
/*
* Adds a new value at the end of the stack
*/
push(value) {
if(value !== ''){
this._storage[this._length] = value;
this._length++;
}
}
/*
* Removes the value at the top of the stack and returns it
*/
pop() {
if(!this.isEmpty()){
const value = this._storage[this._length - 1];
delete this._storage[this._length - 1];
this._length--;
return value;
}
}
/*
* Returns the value at the top of the stack without removing it
*/
peek() {
if(!this.isEmpty()){
return this._storage[this._length - 1];
}
}
/*
* Returns true if the stack is empty else false
*/
isEmpty() {
return this._length === 0;
}
}
const stack = new Stack();
stack.push(5);
stack.peek();
stack.pop();
stack.isEmpty();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment