Skip to content

Instantly share code, notes, and snippets.

@ssippe
Created April 20, 2017 00:33
Show Gist options
  • Save ssippe/1f92625532eef28be6974f898efb23ef to your computer and use it in GitHub Desktop.
Save ssippe/1f92625532eef28be6974f898efb23ef to your computer and use it in GitHub Desktop.
Typescript Cartesian Product
const f = (a: any[], b: any[]): any[] =>
[].concat(...a.map(a2 => b.map(b2 => [].concat(a2, b2))));
export const cartesianProduct = (a: any[], b: any[], ...c: any[]) => {
if (!b || b.length === 0) {
return a;
}
const [b2, ...c2] = c;
const fab = f(a, b);
return cartesianProduct(fab, b2, c2);
};
@albertodiazdorado
Copy link

albertodiazdorado commented Oct 29, 2023

Tell me that you cannot solve the problem of the cartesian product in TypeScript without telling me that you cannot solve the problem of the cartesian product in TypeScript.

Which is fine, by the way. I don't know the solution either. I came here looking for the solution and make the note that the proposed solution is wrong, in the sense explained in the comment above. Nothing else.

If you find the right solution, I'd be glad if you posted it here.

@please-rewrite
Copy link

please-rewrite commented Oct 31, 2023

Mixed types are tricky.
Give this a try.

The key is [...T]

export const cartesianProduct = <T extends any[][]>(a: [...T]): Array<{[K in keyof T]: T[K][number]}> => a.reduce((a, b) => a.flatMap(d => b.map(e => [d, e].flat())))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment