Skip to content

Commit 5ce7e30

Browse files
🚧 progress: First draft.
1 parent 4a20a11 commit 5ce7e30

File tree

5 files changed

+8850
-8
lines changed

5 files changed

+8850
-8
lines changed

Diff for: doc/scripts/header.js

+2-1
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,8 @@ domReady(() => {
1717
header.insertBefore(projectname, header.firstChild);
1818

1919
const testlink = document.querySelector('header > a[data-ice="testLink"]');
20-
testlink.href = 'https://app.codecov.io/gh/async-iterable-iterator/async-iterator-to-array';
20+
testlink.href =
21+
'https://app.codecov.io/gh/async-iterable-iterator/async-iterator-to-array';
2122
testlink.target = '_BLANK';
2223

2324
const searchBox = document.querySelector('.search-box');

Diff for: src/index.js

+19-2
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,19 @@
1-
const answer = 42;
2-
export default answer;
1+
/**
2+
* Spreads an asynchronous iterator inside a new array.
3+
*
4+
* TODO Could be abstracted further with asyncIteratorForEach.
5+
*
6+
* @param {AsyncIterator<any>} asyncIterator - the input iterator.
7+
* @returns {Promise<any[]>} A new array filled with the elements of the input iterator.
8+
*/
9+
export const asyncIteratorToArray = async (asyncIterator) => {
10+
const array = [];
11+
for (;;) {
12+
// eslint-disable-next-line no-await-in-loop
13+
const {done, value} = await asyncIterator.next();
14+
if (done) break;
15+
array.push(value);
16+
}
17+
18+
return array;
19+
};

Diff for: test/src/api.js

-5
This file was deleted.

Diff for: test/src/asyncIteratorToArray.js

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import test from 'ava';
2+
3+
import {asyncIteratorToArray} from '../../src/index.js';
4+
5+
test('works with sync iterator', async (t) => {
6+
const expected = [Math.random(), 3, 'x', {}, new Date()];
7+
const it = expected[Symbol.iterator]();
8+
const actual = await asyncIteratorToArray(it);
9+
t.deepEqual(actual, expected);
10+
});
11+
12+
const asyncify = async function* (array) {
13+
// eslint-disable-next-line no-await-in-loop
14+
for (const x of array) yield await x;
15+
};
16+
17+
const macro = async (t, expected) => {
18+
const asyncIterable = asyncify(expected);
19+
const asyncIterator = asyncIterable[Symbol.asyncIterator]();
20+
const actual = await asyncIteratorToArray(asyncIterator);
21+
t.deepEqual(actual, expected);
22+
};
23+
24+
macro.title = (title, expected) => title ?? JSON.stringify(expected);
25+
26+
test(macro, [1, 2, 3]);
27+
test(macro, [1, Math.random(), 3]);
28+
test(macro, [1, Math.random(), 3]);

0 commit comments

Comments
 (0)