Last active
October 27, 2020 03:09
-
-
Save matsuby/fc988e0f96c16132efabb6f08f8b516e to your computer and use it in GitHub Desktop.
combinations.ts
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
/** | |
* 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