Last active
January 29, 2019 04:49
-
-
Save rxluz/ff257ccd2dd5d08fa13e986d0c0f3a9b to your computer and use it in GitHub Desktop.
JS Data Structures: Stacks, see more at: https://medium.com/p/7dcea711c091
This file contains hidden or 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
function Stack() { | |
let items = [] | |
class PublicStack { | |
peek() { | |
if (this.isEmpty()) throw new Error('Stack is empty') | |
const lastItemIndex = items.length - 1 | |
return items[lastItemIndex] | |
} | |
pop() { | |
if (this.isEmpty()) throw new Error('Stack is empty') | |
items.pop() | |
} | |
push(data) { | |
items.push(data) | |
} | |
isEmpty() { | |
return this.size() === 0 | |
} | |
size() { | |
return items.length | |
} | |
} | |
return new PublicStack() | |
} | |
const myStack = new Stack() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment