-
-
Save hay-kathode/4cf14e07865f63beaafe87adac7a697f 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
"use strict"; | |
function is2dArray(arg) { | |
if (Array.isArray(arg) && arg.length > 0 && arg.every(Array.isArray)) { | |
return true; | |
} else { | |
return false; | |
} | |
} | |
function product(array2d) { | |
if (!is2dArray(array2d)) { | |
throw new RangeError("Invalid argument"); | |
} | |
if (array2d.length === 0) { | |
return [[]]; | |
} else { | |
const head = array2d[0]; | |
const tail = array2d.slice(1); | |
const productTail = tail.length === 0 ? [[]] : product(tail); | |
return head | |
.map((ahead) => productTail.map((atail) => [ahead].concat(atail))) | |
.flat(1); | |
} | |
} | |
exports.product = product; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment