Skip to content

Instantly share code, notes, and snippets.

@gvergnaud
Created May 23, 2022 11:11
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 gvergnaud/9a525881b9fb71c244a528a058c9162f to your computer and use it in GitHub Desktop.
Save gvergnaud/9a525881b9fb71c244a528a058c9162f to your computer and use it in GitHub Desktop.
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