Skip to content

Instantly share code, notes, and snippets.

@aryelgois
Created May 27, 2022 21:46
Show Gist options
  • Save aryelgois/cf21e2d022812df547047a0820ca22b2 to your computer and use it in GitHub Desktop.
Save aryelgois/cf21e2d022812df547047a0820ca22b2 to your computer and use it in GitHub Desktop.
Get combinations of array elements
export function* getCombinations<T>(arr: T[], size: number): Generator<T[]> {
if (size < 1) {
throw new Error('Combination size must be at least 1')
}
if (arr.length === 0) {
yield []
} else if (size === 1) {
for (const el of arr) {
yield [el]
}
} else {
const limit = arr.length - size + 1
for (let i = 0; i < limit; i++) {
for (const result of getCombinations(arr.slice(i + 1), size - 1)) {
yield [arr[i], ...result]
}
}
}
}
export function* getVariableCombinations<T>(arr: T[], min: number, max: number) {
for (let size = min; size <= max; size++) {
yield* getCombinations(arr, size)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment