Created
May 3, 2024 16:44
-
-
Save baetheus/bdc34c598a16b4e34fd97ccb83c1c43d to your computer and use it in GitHub Desktop.
Callbag-ish Range
This file contains hidden or 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
export function range(count: number, start = 0, step = 1): Stream<number> { | |
return (snk) => { | |
let open = true; | |
let index = Math.floor(Math.max(0, count)); | |
let value = start; | |
let readyCount = 0; | |
let pulling = false; | |
const close = () => open = false; | |
const talk = snk((count) => { | |
readyCount += count; | |
pull(); | |
}); | |
function pull() { | |
if (open && !pulling) { | |
pulling = true; | |
// Empty range while open and readyCount not empty | |
while (open && readyCount > 0 && index > 0) { | |
talk.event(value); | |
value += step; | |
readyCount--; | |
index--; | |
} | |
// Reached end of range without closing, close and end | |
if (open && readyCount > 0) { | |
close(); | |
talk.end(); | |
} | |
pulling = false; | |
} | |
} | |
return disposable(close); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment