cmb

A simple combinatorial iterator, supporting a stream of combinations.

Usage no npm install needed!

<script type="module">
  import cmb from 'https://cdn.skypack.dev/cmb';
</script>

README

COMB

the simple combination generator

Combinations generator

Given a set and the number of elements you want to have in a combination, comb returns an iterator object, with the methods next and rewind.

var c = new Comb([1,2,3], 2);
c.next() // {done: false, value: [1,2]}
c.next() // {done: false, value: [1,3]}
c.next() // {done: false, value: [2,3]}
c.next() // {done: true}
c.rewind() // true
c.next() // {done: false, value: [1,2]}

If a callback function is given, it is executed for each element right away.

Comb([1,2,3,4,5], 2, console.log.bind(console));
[ 1, 2 ]
[ 1, 3 ]
[ 1, 4 ]
[ 1, 5 ]
[ 2, 3 ]
[ 2, 4 ]
[ 2, 5 ]
[ 3, 4 ]
[ 3, 5 ]
[ 4, 5 ]

You can also use each to iterate over each combination. You can stop the iteration by returning the generators own break property from within the function. The generator is not rewinded implicitely, so you can resume where you left off, if you want.

var cmb = new Comb([1,2,3,4], 2);
cmb.each(function (val) {
  console.log(val);
  if (val[1] === 3) return cmb.break;
});
console.log("<stopped>");
cmb.each(function (val) {
  console.log(val);
});

[1,2]
[1,3]
<stopped>
[1,4]
[2,3]
[2,4]
[3,4]

Combinations stream

Node.js is pretty strong on streams, so here you have a stream of combinations:

var cstr = Comb.Stream([1,2,3,4,5], 2);

cstr.read() // [ 1, 2 ]
cstr.read() // [ 1, 3 ]
cstr.on('end', console.log.bind(console, 'FIN'));
cstr.on('data', console.log.bind(console));
[ 1, 4 ]
[ 1, 5 ]
[ 2, 3 ]
[ 2, 4 ]
[ 2, 5 ]
[ 3, 4 ]
[ 3, 5 ]
[ 4, 5 ]
null