Skip to content

Instantly share code, notes, and snippets.

@matsuby
Last active October 27, 2020 03:09
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 matsuby/fc988e0f96c16132efabb6f08f8b516e to your computer and use it in GitHub Desktop.
Save matsuby/fc988e0f96c16132efabb6f08f8b516e to your computer and use it in GitHub Desktop.
combinations.ts
/**
* Returns an array of all combinations of elements from all arrays.
*
* @examples
* combinations([1], [2, 3], [4, 5, 6])
* => "[[1,2,4],[1,2,5],[1,2,6],[1,3,4],[1,3,5],[1,3,6]]"
*/
export const combinations = <T extends unknown>(...arrays: T[][]): T[] => {
const result: T[] = []
const _combinations = (n: number, current: T[]) => {
if (n === arrays.length) {
result.push(current as T)
} else {
arrays[n].forEach((item) => _combinations(n + 1, current.concat(item)))
}
}
_combinations(0, [])
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment