Skip to content

Instantly share code, notes, and snippets.

@hay-kathode
Created November 29, 2021 10:28
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 hay-kathode/dd70ca94dcc8b5ae1f229796347f8e94 to your computer and use it in GitHub Desktop.
Save hay-kathode/dd70ca94dcc8b5ae1f229796347f8e94 to your computer and use it in GitHub Desktop.
function is2dArray(arg: any): boolean {
if (Array.isArray(arg) && arg.length > 0 && arg.every(Array.isArray)) {
return true;
} else {
return false;
}
}
export function product<T>(array2d: T[][]): T[][] {
if (!is2dArray(array2d)) {
throw new RangeError("Invalid argument");
}
if (array2d.length === 0) {
return [[]];
} else {
const head: T[] = array2d[0];
const tail: T[][] = array2d.slice(1);
const productTail: T[][] = tail.length === 0 ? [[]] : product(tail);
return head
.map((ahead) => productTail.map((atail) => [ahead].concat(atail)))
.flat(1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment