Skip to content

Instantly share code, notes, and snippets.

@danielrw7
Last active February 22, 2023 13:32
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 danielrw7/df9202305ed14c14280a091709089b29 to your computer and use it in GitHub Desktop.
Save danielrw7/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