-
-
Save Jarvis1010/cb44a4b60e4641543949fb70144cee0c 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
//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