Skip to content

Instantly share code, notes, and snippets.

@cybercase
Last active February 10, 2023 10:59
Show Gist options
  • Save cybercase/db7dde901d7070c98c48 to your computer and use it in GitHub Desktop.
Save cybercase/db7dde901d7070c98c48 to your computer and use it in GitHub Desktop.
Python-like itertools.product function in javascript
function product() {
var args = Array.prototype.slice.call(arguments); // makes array from arguments
return args.reduce(function tl (accumulator, value) {
var tmp = [];
accumulator.forEach(function (a0) {
value.forEach(function (a1) {
tmp.push(a0.concat(a1));
});
});
return tmp;
}, [[]]);
}
console.log(product([1], [2, 3], ['a', 'b']));
@gaspardfeuvray
Copy link

gaspardfeuvray commented Jun 11, 2022

Generic version for Typescript:

const combinations = <T>(sets: T[][]): T[][] => {
  if (sets.length === 1) {
    return sets[0].map((el) => [el]);
  } else
    return sets[0].flatMap((val) =>
      combinations(sets.slice(1)).map((c): T[] => [val].concat(c))
    );
};

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