Last active
February 22, 2023 13:32
-
-
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
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
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) | |
} | |
} | |
}, | |
] | |
} |
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
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