Skip to content

Instantly share code, notes, and snippets.

@Jarvis1010
Last active November 29, 2021 18:22
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/b2538c00353c155e110845d61195ec85 to your computer and use it in GitHub Desktop.
Save Jarvis1010/b2538c00353c155e110845d61195ec85 to your computer and use it in GitHub Desktop.
class ImmutableStack {
#head;
constructor(node){
this.#head = node
}
push(value){
const node = {
value,
next : this.#head
}
return new ImmutableStack(node)
}
peak(){
return this.#head?.value
}
pop(){
const safeNode = this.#head ?? {}
return new ImmutableStack(safeNode.next);
}
[Symbol.iterator]=function*(){
let safeNode = this.#head ?? {}
while(safeNode.value){
yield safeNode.value
safeNode = safeNode.next ?? {}
}
}
}
let stack = new Stack()
stack = stack.push(1)
stack = stack.push(2)
stack.peak() // 2
stack = stack.pop()
stack.peak() // 1
stack = stack.push(3)
stack = stack.push(4)
stack = stack.push(2)
stack = 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