UNPKG

iteragain

Version:

Javascript Iterable/Iterator/Generator-function utilities.

53 lines 2.25 kB
import RangeIterator from './RangeIterator'; import toArray from '../toArray'; /** Returns all successive `size` length permutations of the input `iterator`. */ var PermutationsIterator = /** @class */ (function () { function PermutationsIterator(iterator, size) { this.started = false; this.pool = toArray(iterator); this.size = size !== null && size !== void 0 ? size : this.pool.length; if (this.size > this.pool.length) this.next = function () { return ({ done: true, value: undefined }); }; this.indices = toArray(new RangeIterator(0, this.pool.length)); this.cycles = toArray(new RangeIterator(this.pool.length, this.pool.length - this.size, -1)); } Object.defineProperty(PermutationsIterator.prototype, "value", { get: function () { var _this = this; return this.indices.slice(0, this.size).map(function (i) { return _this.pool[i]; }); }, enumerable: false, configurable: true }); PermutationsIterator.prototype[Symbol.iterator] = function () { return this; }; PermutationsIterator.prototype.next = function () { var _a; if (!this.started) { this.started = true; return { done: false, value: this.value }; } for (var i = this.size - 1; i > -1; i--) { this.cycles[i]--; if (this.cycles[i] === 0) { var first = this.indices[i]; for (var 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 { var j = this.cycles[i]; var negJ = this.pool.length - j; _a = [this.indices[negJ], this.indices[i]], this.indices[i] = _a[0], this.indices[negJ] = _a[1]; return { done: false, value: this.value }; } } return { done: true, value: undefined }; }; return PermutationsIterator; }()); export { PermutationsIterator }; export default PermutationsIterator; //# sourceMappingURL=PermutationsIterator.js.map