Skip to content

Commit 8e8c097

Browse files
committed
feat(asyncConcatOnce): add asyncConcatOnce function
1 parent 9fd4cd4 commit 8e8c097

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

index.test.ts

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import {
55
asyncAndOnce,
66
asyncAnyOnce,
77
asyncAverageOnce,
8+
asyncConcatOnce,
89
asyncContainsOnce,
910
asyncDropOnce,
1011
asyncDropUntilOnce,
@@ -510,3 +511,25 @@ test("asyncAllOnce", async t => {
510511
t.true(await asyncAllOnce(asyncIterator([1, 2, 3]), e => e < 4));
511512
t.false(await asyncAllOnce(asyncIterator([1, 2, 3]), e => e > 2));
512513
});
514+
515+
test("asyncConcatOnce", async t => {
516+
t.deepEqual(
517+
await asyncToArrayOnce(
518+
asyncConcatOnce(
519+
asyncIterator([
520+
asyncIterator([1, 2]),
521+
asyncIterator([]),
522+
asyncIterator([3]),
523+
asyncIterator([4, 5])
524+
])
525+
)
526+
),
527+
[1, 2, 3, 4, 5]
528+
);
529+
t.deepEqual(
530+
await asyncToArrayOnce(
531+
asyncConcatOnce(asyncIterator([asyncIterator([]), asyncIterator([])]))
532+
),
533+
[]
534+
);
535+
});

index.ts

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -993,3 +993,39 @@ export function asyncAllOnceFn<T>(
993993
): (iterator: AsyncIteratorLike<T>) => Promise<boolean> {
994994
return async iterator => asyncAllOnce(iterator, predicate);
995995
}
996+
997+
export function asyncConcatOnce<T>(
998+
iterators: AsyncIteratorLike<AsyncIteratorLike<T>>
999+
): AsyncIterator<T> {
1000+
const its = asyncIterator(iterators);
1001+
const done: IteratorResult<T> = {done: true, value: undefined};
1002+
const first = async (): Promise<IteratorResult<T>> => {
1003+
const itElement = await its.next();
1004+
if (itElement.done === true) {
1005+
next = after;
1006+
return done;
1007+
} else {
1008+
next = during(asyncIterator(itElement.value));
1009+
return next();
1010+
}
1011+
};
1012+
const during = (iterator: AsyncIterator<T>) => async (): Promise<IteratorResult<T>> => {
1013+
let element = await iterator.next();
1014+
while (element.done === true) {
1015+
const itElement = await its.next();
1016+
if (itElement.done === true) {
1017+
next = after;
1018+
return done;
1019+
} else {
1020+
const iterator = asyncIterator(itElement.value);
1021+
next = during(iterator);
1022+
element = await iterator.next();
1023+
}
1024+
}
1025+
1026+
return element;
1027+
};
1028+
const after = async (): Promise<IteratorResult<T>> => done;
1029+
let next = first;
1030+
return {next: async () => next()};
1031+
}

0 commit comments

Comments
 (0)