iter-tools-es
Version:
The iterable toolbox
80 lines (68 loc) • 1.68 kB
JavaScript
const {
IterableIterator
} = require('./iterable-iterator.js');
const {
AsyncPartsIterator
} = require('./async-parts-iterator.js');
class AsyncBisector extends IterableIterator {
constructor(source, strategy, options) {
super();
this.source = source;
this.strategy = strategy;
this.options = options;
this.partsIterator = null;
this.firstPart = null;
this.secondPart = null;
this.currentIdx = 0;
}
async setupFirst() {
const {
source,
strategy,
options
} = this;
this.partsIterator = this.partsIterator || new AsyncPartsIterator(source, strategy, options);
if (!this.firstPart) {
const step = await this.partsIterator.next();
this.firstPart = step.done ? [] : step.value;
}
}
next() {
const self = this;
switch (this.currentIdx++) {
case 0:
return {
value: async function* () {
await self.setupFirst();
yield* self.firstPart;
}(),
done: false
};
case 1:
return {
value: async function* () {
await self.setupFirst();
const step = await self.partsIterator.next();
self.secondPart = step.done ? [] : step.value;
yield* self.secondPart;
}(),
done: false
};
default:
return {
value: undefined,
done: true
};
}
}
return() {
if (this.currentIdx === 1) {
throw new Error('You must take both parts of a bisector or neither.');
}
return {
value: undefined,
done: true
};
}
}
exports.AsyncBisector = AsyncBisector;