Skip to content

Instantly share code, notes, and snippets.

@rxluz
Last active January 29, 2019 04:49
Show Gist options
  • Save rxluz/ff257ccd2dd5d08fa13e986d0c0f3a9b to your computer and use it in GitHub Desktop.
Save rxluz/ff257ccd2dd5d08fa13e986d0c0f3a9b to your computer and use it in GitHub Desktop.
JS Data Structures: Stacks, see more at: https://medium.com/p/7dcea711c091
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