iteragain
Version:
Javascript Iterable/Iterator/Generator-function utilities.
54 lines • 2.47 kB
JavaScript
import toArray from '../toArray';
/** Creates `size` length subsequences from the input `iterator`. */
var CombinationsIterator = /** @class */ (function () {
function CombinationsIterator(iterator, size, withReplacement) {
this.size = size;
this.withReplacement = withReplacement;
this.i = 0;
this.pool = toArray(iterator);
this.n = this.pool.length;
if (this.n < this.size)
this.next = function () { return ({ done: true, value: undefined }); };
this.indices = this.withReplacement ? new Array(this.size).fill(0) : Array.from({ length: this.size }, function (_, i) { return i; });
this.indices[this.indices.length - 1]--; // So that the first combination will start at the correct spot.
}
Object.defineProperty(CombinationsIterator.prototype, "value", {
get: function () {
var _this = this;
return this.indices.map(function (i) { return _this.pool[i]; });
},
enumerable: false,
configurable: true
});
CombinationsIterator.prototype[Symbol.iterator] = function () {
return this;
};
CombinationsIterator.prototype.next = function () {
if (this.withReplacement) {
for (this.i = this.size - 1; this.i > -1; this.i--)
if (this.indices[this.i] !== this.n - 1)
break;
// If the previous for loop finished without breaking, then we've exhausted all combinations:
if (this.i === -1)
return { done: true, value: undefined };
var v = this.indices[this.i] + 1;
for (var j = this.i; j < this.size; j++)
this.indices[j] = v;
return { done: false, value: this.value };
}
for (this.i = this.size - 1; this.i > -1; this.i--)
if (this.indices[this.i] !== this.i + this.n - this.size)
break;
// If the previous for loop finished without breaking, then we've exhausted all combinations:
if (this.i === -1)
return { done: true, value: undefined };
this.indices[this.i]++;
for (var j = this.i + 1; j < this.size; j++)
this.indices[j] = this.indices[j - 1] + 1;
return { done: false, value: this.value };
};
return CombinationsIterator;
}());
export { CombinationsIterator };
export default CombinationsIterator;
//# sourceMappingURL=CombinationsIterator.js.map