-
-
Save hay-kathode/dd70ca94dcc8b5ae1f229796347f8e94 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
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