UNPKG

iter-tools-es

Version:
100 lines (79 loc) 1.58 kB
const { asyncEnsureIterable, asyncCallReturn } = require('./async-iterable.js'); const _ = Symbol.for('_'); class AsyncPeekeratorIterator { constructor(peekr) { this.peekr = peekr; } async next() { const { peekr } = this; const { current } = peekr; await peekr.advance(); return current; } async return() { await this.peekr.return(); return { value: undefined, done: true }; } [Symbol.asyncIterator]() { return this; } } class AsyncPeekerator { static async from(iterable, ...args) { const iterator = asyncEnsureIterable(iterable)[Symbol.asyncIterator](); const first = await 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; } async advance() { const this_ = this[_]; if (!this_.current.done) { this_.index++; this_.current = await this_.iterator.next(); } return this; } async return() { const this_ = this[_]; if (!this.done) { await asyncCallReturn(this_.iterator); } this_.current = { value: undefined, done: true }; return this; } asIterator() { return new AsyncPeekeratorIterator(this); } } exports.AsyncPeekerator = AsyncPeekerator;