Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions asynciterator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1852,6 +1852,22 @@ class HistoryReader<T> {
}
}

class WrapIterator<T> extends AsyncIterator<T> {
constructor(private source: Iterator<T>) {
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.
Expand All @@ -1865,6 +1881,18 @@ export function wrap<T>(source: EventEmitter | Promise<EventEmitter>, options?:
return new TransformIterator<T>(source as AsyncIterator<T> | Promise<AsyncIterator<T>>, 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<T>(source: Iterator<T>) {
return new WrapIterator(source);
}

/**
Creates an empty iterator.
*/
Expand Down
13 changes: 13 additions & 0 deletions test/WrapIterator-test.js
Original file line number Diff line number Diff line change
@@ -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]);
});
});