-
-
Save Jarvis1010/b2538c00353c155e110845d61195ec85 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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