Last active
December 1, 2020 07:59
-
-
Save itsMapleLeaf/21055f4e120768f2dcb4ed977d268895 to your computer and use it in GitHub Desktop.
iterable helpers??
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
| // @ts-check | |
| /** | |
| * @template T | |
| * @param {Iterable<T>} iterable the collection of items for which to make combinations of | |
| * @param {number} size the size of each combination | |
| * @return {Iterable<Set<T>>} an iterable of sets for each combination | |
| */ | |
| function* combinations(iterable, size) { | |
| if (size < 1) return | |
| if (size === 1) { | |
| for (const item of iterable) { | |
| yield new Set([item]) | |
| } | |
| } | |
| for (const [index, item] of entries(iterable)) { | |
| for (const rest of combinations(skip(iterable, index), size)) { | |
| const combination = new Set([item, ...rest]) | |
| if (combination.size === size) yield combination | |
| } | |
| } | |
| } | |
| /** | |
| * @template T | |
| * @param {Iterable<T>} iterable | |
| * @return {Iterable<readonly [number, T]>} | |
| */ | |
| function* entries(iterable) { | |
| let i = 0 | |
| for (const item of iterable) yield [i++, item] | |
| } | |
| /** | |
| * @template T | |
| * @param {Iterable<T>} iterable | |
| * @param {number} count | |
| * @return {Iterable<T>} | |
| */ | |
| function* skip(iterable, count) { | |
| for (const [index, item] of entries(iterable)) { | |
| if (index >= count) yield item | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment