Created
May 23, 2022 11:11
-
-
Save gvergnaud/9a525881b9fb71c244a528a058c9162f to your computer and use it in GitHub Desktop.
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
type TupleToList<xs> = xs extends [infer head, ...(infer tail)] | |
? [head extends any[] ? head[number] : never, ...TupleToList<tail>] | |
: []; | |
function permute<xs extends [] | [any[], ...any[][]]>([ | |
head, | |
...rest | |
]: xs): TupleToList<xs>[]; | |
function permute<T>([head, ...rest]: T[][]): T[][]; | |
function permute<T>([head, ...rest]: T[][]): T[][] { | |
if (!head) return [[]]; | |
if (!rest.length) return head.map((x) => [x]); | |
return head.flatMap((item) => permute(rest).map((perm) => [item, ...perm])); | |
} | |
console.log(permute([])); // -> [] | |
console.log(permute([[1, 2, 3]])); // -> [[1], [2], [3]] | |
console.log( | |
permute([ | |
[1, 2, 3], | |
["a", "b"] | |
]) | |
); // -> [[1, "a"], [1, "b"], [2, "a"], [2, "b"], [3, "a"], [3, "b"]] | |
console.log( | |
permute([ | |
[1, 2, 3], | |
["a", "b", "c"], | |
[true, false] | |
]) | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment