Skip to content

Commit 4a9acc0

Browse files
committed
feat(asyncZipOnce): add asyncZipOnce function
1 parent a677639 commit 4a9acc0

File tree

2 files changed

+44
-1
lines changed

2 files changed

+44
-1
lines changed

index.test.ts

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,8 @@ import {
5252
asyncTakeUntilOnce,
5353
asyncTakeWhileOnce,
5454
asyncToArrayOnce,
55-
asyncUnshiftOnce
55+
asyncUnshiftOnce,
56+
asyncZipOnce
5657
} from "./index";
5758

5859
test("asyncIterator(empty)", async t => {
@@ -624,3 +625,16 @@ test("asyncPairwiseOnce", async t => {
624625
[4, 5]
625626
]);
626627
});
628+
629+
test("asyncZipOnce", async t => {
630+
t.deepEqual(
631+
await asyncToArrayOnce(
632+
asyncZipOnce(asyncIterator([1, 2, 3]), asyncIterator([6, 5, 4, 3, 2, 1]))
633+
),
634+
[
635+
[1, 6],
636+
[2, 5],
637+
[3, 4]
638+
]
639+
);
640+
});

index.ts

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1171,3 +1171,32 @@ export function asyncPairwiseOnce<T>(
11711171
let next = before;
11721172
return {next: async () => next()};
11731173
}
1174+
1175+
export function asyncZipOnce<T, U>(
1176+
a: AsyncIteratorLike<T>,
1177+
b: AsyncIteratorLike<U>
1178+
): AsyncIterator<readonly [T, U]> {
1179+
const ait = asyncIterator(a);
1180+
const bit = asyncIterator(b);
1181+
const during = async (): Promise<IteratorResult<readonly [T, U]>> => {
1182+
const [aElement, bElement] = await Promise.all([ait.next(), bit.next()] as const);
1183+
if (aElement.done === true || bElement.done === true) {
1184+
next = after;
1185+
return after();
1186+
} else {
1187+
return {value: [aElement.value, bElement.value]};
1188+
}
1189+
};
1190+
const after = async (): Promise<IteratorResult<readonly [T, U]>> => ({
1191+
done: true,
1192+
value: undefined
1193+
});
1194+
let next = during;
1195+
return {next: async () => next()};
1196+
}
1197+
1198+
export function asyncZipOnceFn<T, U>(
1199+
b: AsyncIteratorLike<U>
1200+
): (a: AsyncIteratorLike<T>) => AsyncIterator<readonly [T, U]> {
1201+
return a => asyncZipOnce(a, b);
1202+
}

0 commit comments

Comments
 (0)