iteragain
Version:
Javascript Iterable/Iterator/Generator-function utilities.
49 lines • 1.66 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.GroupByIterator = void 0;
/** Groups values in the input iterator by some key identifier function or property. */
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];
}
}
exports.GroupByIterator = GroupByIterator;
exports.default = GroupByIterator;
//# sourceMappingURL=GroupByIterator.js.map