UNPKG

iteragain

Version:

Javascript Iterable/Iterator/Generator-function utilities.

45 lines 1.51 kB
/** Groups values in the input iterator by some key identifier function or property. */ export class GroupByIterator { constructor(iterator, key) { this.iterator = iterator; this.key = key; this.currGroup = []; this.done = false; } [Symbol.iterator]() { return this; } next() { if (this.done) return { done: true, value: undefined }; let next; if (this.currKey === undefined) { next = this.iterator.next(); if (next.done) { this.done = true; return { done: true, value: undefined }; } this.currKey = this.getKey(next.value); this.currGroup.push(next.value); } while (!(next = this.iterator.next()).done) { this.currGroup.push(next.value); const nextKey = this.getKey(next.value); if (nextKey !== this.currKey) { const value = [ this.currKey, this.currGroup.splice(0, this.currGroup.length - 1), ]; this.currKey = nextKey; return { done: false, value }; } } this.done = true; return { done: false, value: [this.currKey, this.currGroup] }; } getKey(value) { return typeof this.key === 'function' ? this.key(value) : value[this.key]; } } export default GroupByIterator; //# sourceMappingURL=GroupByIterator.js.map