Skip to content

Instantly share code, notes, and snippets.

@Jarvis1010
Last active November 29, 2021 18:53
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/7a1b5df2ff83f0ea9f40322482103fe3 to your computer and use it in GitHub Desktop.
Save Jarvis1010/7a1b5df2ff83f0ea9f40322482103fe3 to your computer and use it in GitHub Desktop.
const stackUtils = {
push(head, value){
const node = {
value,
next : head
}
return node
},
peak(head){
return head?.value
},
pop(head){
const safeNode = head ?? {}
return safeNode.next;
},
getIterator(head){
return (function*(){
let safeNode = head ?? {}
while(safeNode.value){
yield safeNode.value
safeNode = safeNode.next ?? {}
}
})()
}
}
let stack
stack = stackUtils.push(stack, 1)
stack = stackUtils.push(stack, 2)
stackUtils.peak(stack) // 2
stack = stackUtils.pop(stack)
stackUtils.peak(stack) // 1
stack = stackUtils.push(stack, 3)
stack = stackUtils.push(stack, 4)
stack = stackUtils.push(stack, 2)
stack = stackUtils.push(stack, 2)
console.log([...stackUtils.getIterator(stack)]) // [ 2, 2, 4, 3, 1 ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment