diff --git a/asynciterator.ts b/asynciterator.ts index 15aaed1..a7fdfe9 100644 --- a/asynciterator.ts +++ b/asynciterator.ts @@ -1852,6 +1852,22 @@ class HistoryReader { } } +class WrapIterator extends AsyncIterator { + constructor(private source: Iterator) { + super(); + this.readable = true; + } + + read(): T | null { + const item = this.source.next(); + if (item.done) { + this.close(); + return null; + } + return item.value; + } +} + /** Creates an iterator that wraps around a given iterator or readable stream. Use this to convert an iterator-like object into a full-featured AsyncIterator. @@ -1865,6 +1881,18 @@ export function wrap(source: EventEmitter | Promise, options?: return new TransformIterator(source as AsyncIterator | Promise>, options); } +/** + Creates an iterator that wraps around a given synchronous iterator. + Use this to convert an iterator-like object into a full-featured AsyncIterator. + After this operation, only read the returned iterator instead of the given one. + @function + @param {Iterator} [source] The source this iterator generates items from + @returns {module:asynciterator.AsyncIterator} A new iterator with the items from the given iterator +*/ +export function wrapIterator(source: Iterator) { + return new WrapIterator(source); +} + /** Creates an empty iterator. */ diff --git a/test/WrapIterator-test.js b/test/WrapIterator-test.js new file mode 100644 index 0000000..a7adec1 --- /dev/null +++ b/test/WrapIterator-test.js @@ -0,0 +1,13 @@ +import { + wrapIterator, +} from '../dist/asynciterator.js'; + +describe('wrapIterator', () => { + it('Should wrap correctly', async () => { + (await wrapIterator((function * () { + yield 1; + yield 2; + yield 3; + })()).toArray()).should.deep.equal([1, 2, 3]); + }); +});