iter-tools-es
Version:
The iterable toolbox
100 lines (79 loc) • 1.46 kB
JavaScript
const {
ensureIterable,
callReturn
} = require('./iterable.js');
const _ = Symbol.for('_');
class PeekeratorIterator {
constructor(peekr) {
this.peekr = peekr;
}
next() {
const {
peekr
} = this;
const {
current
} = peekr;
peekr.advance();
return current;
}
return() {
this.peekr.return();
return {
value: undefined,
done: true
};
}
[Symbol.iterator]() {
return this;
}
}
class Peekerator {
static from(iterable, ...args) {
const iterator = ensureIterable(iterable)[Symbol.iterator]();
const first = iterator.next();
return new this(iterator, first, ...args);
}
constructor(iterator, first) {
this[_] = {
iterator,
current: first,
index: 0
};
}
get current() {
return this[_].current;
}
get value() {
return this[_].current.value;
}
get done() {
return this[_].current.done;
}
get index() {
return this[_].index;
}
advance() {
const this_ = this[_];
if (!this_.current.done) {
this_.index++;
this_.current = this_.iterator.next();
}
return this;
}
return() {
const this_ = this[_];
if (!this.done) {
callReturn(this_.iterator);
}
this_.current = {
value: undefined,
done: true
};
return this;
}
asIterator() {
return new PeekeratorIterator(this);
}
}
exports.Peekerator = Peekerator;