iter-tools-es
Version:
The iterable toolbox
80 lines (68 loc) • 1.61 kB
JavaScript
const {
IterableIterator
} = require('./iterable-iterator.js');
const {
PartsIterator
} = require('./parts-iterator.js');
class Bisector 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;
}
setupFirst() {
const {
source,
strategy,
options
} = this;
this.partsIterator = this.partsIterator || new PartsIterator(source, strategy, options);
if (!this.firstPart) {
const step = this.partsIterator.next();
this.firstPart = step.done ? [] : step.value;
}
}
next() {
const self = this;
switch (this.currentIdx++) {
case 0:
return {
value: function* () {
self.setupFirst();
yield* self.firstPart;
}(),
done: false
};
case 1:
return {
value: function* () {
self.setupFirst();
const step = 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.Bisector = Bisector;