Skip to content

Instantly share code, notes, and snippets.

@Jarvis1010
Last active November 29, 2021 19:15
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/cb44a4b60e4641543949fb70144cee0c to your computer and use it in GitHub Desktop.
Save Jarvis1010/cb44a4b60e4641543949fb70144cee0c to your computer and use it in GitHub Desktop.
//stackUtils.js
export function peak(head){
return head?.value
}
export function pop(head){
const safeNode = head ?? {}
return safeNode.next;
}
export function push(head){
return (value) => {
const node = {
value,
next : head
}
return node
}
}
export function getIterator(head){
return (function*(){
let safeNode = head ?? {}
while(safeNode.value){
yield safeNode.value
safeNode = safeNode.next ?? {}
}
})()
}
// index.js
import {push, pop, peak, getIterator} from './stackUtils.js'
let stack
stack = push(stack)(1)
stack = push(stack)(2)
peak(stack) // 2
stack = pop(stack)
peak(stack) // 1
stack = push(stack)(3)
stack = push(stack)(4)
stack = push(stack)(2)
let stackPusher = push(stack)
stack = stackPusher(2)
console.log([...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