Skip to content

Instantly share code, notes, and snippets.

@ramsunvtech
Created August 13, 2019 17:37
Show Gist options
  • Save ramsunvtech/cd695a010e6bd15288c295f59cb443dd to your computer and use it in GitHub Desktop.
Save ramsunvtech/cd695a010e6bd15288c295f59cb443dd to your computer and use it in GitHub Desktop.
Stack.js
// Stack -
// Push - Add value at end
// Pop - Remove and return the end of the stack
// Peek - Return the end value of the stack
// Size - Return the size
function Stack() {
let count = 0;
let storage = {};
return {
push: (value) => {
storage[count] = value;
count++;
},
pop: () => {
count--;
const poppedValue = storage[count];
delete storage[count];
return poppedValue;
},
peek: () => storage[count - 1],
size: () => count,
}
}
const myStack = Stack();
myStack.push(1);
myStack.push(2);
console.log('Peek: ', myStack.peek());
console.log('Pop: ', myStack.pop());
console.log('Peek: ', myStack.peek());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment