Created
August 13, 2019 17:37
-
-
Save ramsunvtech/cd695a010e6bd15288c295f59cb443dd to your computer and use it in GitHub Desktop.
Stack.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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