Skip to content

Instantly share code, notes, and snippets.

@Jarvis1010
Last active Nov 29, 2021
Embed
What would you like to do?
class Stack {
#head;
push(value){
const node = {
value,
next : this.#head
}
this.#head = node
}
peak(){
return this.#head?.value
}
pop(){
const safeNode = this.#head ?? {}
const poppedValue = safeNode.value;
this.#head = safeNode.next;
return poppedValue;
}
[Symbol.iterator]=function*(){
let safeNode = this.#head ?? {}
while(safeNode.value){
yield safeNode.value
safeNode = safeNode.next ?? {}
}
}
}
const stack = new Stack()
stack.push(1)
stack.push(2)
stack.peak() // 2
stack.pop() // 2
stack.peak() // 1
stack.push(3)
stack.push(4)
stack.push(2)
stack.push(2)
console.log([...stack]) // [ 2, 2, 4, 3, 1 ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment