Skip to content

Commit ee6570e

Browse files
committed
feat(asyncFoldOnce): add asyncFoldOnce function
1 parent 092afe1 commit ee6570e

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

index.test.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import {
1010
asyncExcludeNullOnce,
1111
asyncExcludeOnce,
1212
asyncFilterOnce,
13+
asyncFoldOnce,
1314
asyncInitialOnce,
1415
asyncIterator,
1516
asyncLastOnce,
@@ -405,3 +406,7 @@ test("asyncRemoveFirstOnce", async t => {
405406
[1, 2, 4, 3, 2, 1]
406407
);
407408
});
409+
410+
test("asyncFoldOnce", async t => {
411+
t.is(await asyncFoldOnce(asyncIterator([1, 2, 3]), (a, e, i) => a + e * i, 0), 8);
412+
});

index.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -624,3 +624,27 @@ export function asyncRemoveFirstOnceFn<T>(
624624
): (iterator: AsyncIteratorLike<T>) => AsyncIterator<T> {
625625
return iterator => asyncRemoveFirstOnce(iterator, value);
626626
}
627+
628+
export async function asyncFoldOnce<T, U>(
629+
iterator: AsyncIteratorLike<T>,
630+
f: (accumulator: U, element: T, index: number) => U | Promise<U>,
631+
initial: U | Promise<U>
632+
): Promise<U> {
633+
const it = asyncIterator(iterator);
634+
let [element, accumulator] = await Promise.all([it.next(), initial] as const);
635+
let i = 0;
636+
while (element.done !== true) {
637+
[accumulator, element] = await Promise.all([
638+
f(accumulator, element.value, i++),
639+
it.next()
640+
] as const);
641+
}
642+
return accumulator;
643+
}
644+
645+
export function asyncFoldOnceFn<T, U>(
646+
f: (accumulator: U, element: T, index: number) => U | Promise<U>,
647+
initial: U | Promise<U>
648+
): (iterator: AsyncIteratorLike<T>) => Promise<U> {
649+
return async iterator => asyncFoldOnce(iterator, f, initial);
650+
}

0 commit comments

Comments
 (0)