Skip to content

Instantly share code, notes, and snippets.

@hay-kathode
Created November 29, 2021 10:38
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/4cf14e07865f63beaafe87adac7a697f to your computer and use it in GitHub Desktop.
Save hay-kathode/4cf14e07865f63beaafe87adac7a697f to your computer and use it in GitHub Desktop.
"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