UNPKG

iteragain

Version:

Javascript Iterable/Iterator/Generator-function utilities.

36 lines 1.28 kB
/** An iterator that yields non-overlapping values in chunks (tuples) of a certain `size`. */ export class ChunksIterator { constructor(iterator, length, fill) { this.iterator = iterator; this.length = length; this.fill = fill; this.done = false; this.chunk = []; if (length <= 0) throw new RangeError('length must be greater than 0'); } [Symbol.iterator]() { return this; } next(...args) { if (this.done) return { done: true, value: undefined }; for (let i = 0; i < this.length; i++) { const next = this.iterator.next(...args); if (next.done) { this.done = true; if (this.chunk.length) { if (this.fill !== undefined) { this.chunk = this.chunk.concat(Array.from({ length: this.length - this.chunk.length }, _ => this.fill)); } break; } return { done: true, value: undefined }; } this.chunk.push(next.value); } return { done: false, value: this.chunk.splice(0, this.length) }; } } export default ChunksIterator; //# sourceMappingURL=ChunksIterator.js.map