Lazy creation of all combinations of a array of arbitrary length

1 min read Original article ↗

Lazy creation of all combinations of a array of arbitrary length

An array with the length of 16 has 16! possible combinations (2.092279e+13), if one would like to operate on this set of combinations it is neccessary to generate all of them upfront. This alternative approach using ECMA6 generators creates these combinations on demand thus being extremely memory efficient.

var iterator = combinations([1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13]);
var handle = setInterval(function() {
var next = iterator.next();
if (next.done) {
clearInterval(handle);
} else {
console.log(next.value);
}
}, 1000);
function* combinations(input) {
if (input.length == 1) {
yield input;
return;
}
var result = [];
for(var i = 0; i < input.length; i++) {
var subResult = [];
var tail = input.concat([]);
var head = input[i];
tail.splice(i, 1);
for (var combination of combinations(tail)) {
yield [head].concat(combination);
}
}
}