Skip to content

Instantly share code, notes, and snippets.

@postpostscript
Last active February 22, 2023 13:32
Show Gist options
  • Save postpostscript/df9202305ed14c14280a091709089b29 to your computer and use it in GitHub Desktop.
Save postpostscript/df9202305ed14c14280a091709089b29 to your computer and use it in GitHub Desktop.
add items to a generator while looping through each unique element of it
function appendableSetGenerator<T>(initialToTry?: IterableIterator<T>, tried = new Set<T>()): [Generator<T>, (...values: T[]) => void] {
const toTry = new Set<T>(initialToTry || null)
return [
(function* () {
while (toTry.size) {
for (const value of toTry.values()) {
tried.add(value)
toTry.delete(value)
yield value
break
}
}
})(),
(...values) => {
for (const value of values) {
if (!tried.has(value)) {
toTry.add(value)
}
}
},
]
}
const [elems, addToElems] = appendableSetGenerator<number>()
for (const elem in elems) {
// do something
addToElems(...)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment