Skip to content

Instantly share code, notes, and snippets.

@rxluz
Last active January 29, 2019 04:49
Show Gist options
  • Save rxluz/ef9dabe16d4024d0633044821b519138 to your computer and use it in GitHub Desktop.
Save rxluz/ef9dabe16d4024d0633044821b519138 to your computer and use it in GitHub Desktop.
JS Data Structures: Stacks, see more at: https://medium.com/p/7dcea711c091
function Stack() {
let top = null
let size = 0
class Node {
constructor(data) {
this.data = data
this.previous = null
}
}
class PublicStack {
push(data) {
const node = new Node(data)
node.previous = top
top = node
size++
return this.top
}
pop() {
if (this.isEmpty()) throw new Error('This stack is empty')
const temp = top
top = top.previous
size--
return temp
}
peek() {
if (this.isEmpty()) throw new Error('This stack is empty')
return top.data
}
isEmpty() {
return size === 0
}
clear() {
top = null
}
size() {
return size
}
}
return new PublicStack()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment