Skip to content

Instantly share code, notes, and snippets.

@Jarvis1010
Last active November 29, 2021 17:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Jarvis1010/43a0d779268a4a837b0b710ecbd01ab3 to your computer and use it in GitHub Desktop.
Save Jarvis1010/43a0d779268a4a837b0b710ecbd01ab3 to your computer and use it in GitHub Desktop.
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