iteragain
Version:
Javascript Iterable/Iterator/Generator-function utilities.
49 lines • 2.06 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PermutationsIterator = void 0;
const RangeIterator_1 = require("./RangeIterator");
const toArray_1 = require("../toArray");
/** Returns all successive `size` length permutations of the input `iterator`. */
class PermutationsIterator {
constructor(iterator, size) {
this.started = false;
this.pool = (0, toArray_1.default)(iterator);
this.size = size !== null && size !== void 0 ? size : this.pool.length;
if (this.size > this.pool.length)
this.next = () => ({ done: true, value: undefined });
this.indices = (0, toArray_1.default)(new RangeIterator_1.default(0, this.pool.length));
this.cycles = (0, toArray_1.default)(new RangeIterator_1.default(this.pool.length, this.pool.length - this.size, -1));
}
get value() {
return this.indices.slice(0, this.size).map(i => this.pool[i]);
}
[Symbol.iterator]() {
return this;
}
next() {
if (!this.started) {
this.started = true;
return { done: false, value: this.value };
}
for (let i = this.size - 1; i > -1; i--) {
this.cycles[i]--;
if (this.cycles[i] === 0) {
const first = this.indices[i];
for (let j = i; j < this.indices.length - 1; j++)
this.indices[j] = this.indices[j + 1];
this.indices[this.indices.length - 1] = first;
this.cycles[i] = this.pool.length - i;
}
else {
const j = this.cycles[i];
const negJ = this.pool.length - j;
[this.indices[i], this.indices[negJ]] = [this.indices[negJ], this.indices[i]];
return { done: false, value: this.value };
}
}
return { done: true, value: undefined };
}
}
exports.PermutationsIterator = PermutationsIterator;
exports.default = PermutationsIterator;
//# sourceMappingURL=PermutationsIterator.js.map