Skip to content

Commit 33ad70f

Browse files
committed
feat(asyncFold1Once): add asyncFold1Once function
1 parent ee6570e commit 33ad70f

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+
asyncFold1Once,
1314
asyncFoldOnce,
1415
asyncInitialOnce,
1516
asyncIterator,
@@ -410,3 +411,7 @@ test("asyncRemoveFirstOnce", async t => {
410411
test("asyncFoldOnce", async t => {
411412
t.is(await asyncFoldOnce(asyncIterator([1, 2, 3]), (a, e, i) => a + e * i, 0), 8);
412413
});
414+
415+
test("asyncFold1Once", async t => {
416+
t.is(await asyncFold1Once(asyncIterator([1, 2, 3]), (a, e, i) => a + e * i), 9);
417+
});

index.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -648,3 +648,27 @@ export function asyncFoldOnceFn<T, U>(
648648
): (iterator: AsyncIteratorLike<T>) => Promise<U> {
649649
return async iterator => asyncFoldOnce(iterator, f, initial);
650650
}
651+
652+
export async function asyncFold1Once<T>(
653+
iterator: AsyncIteratorLike<T>,
654+
f: (accumulator: T, element: T, index: number) => T | Promise<T>
655+
): Promise<T> {
656+
const it = asyncIterator(iterator);
657+
const element = await it.next();
658+
659+
if (element.done === true) {
660+
throw new TypeError("asyncFold1Once: empty AsyncIterator");
661+
}
662+
663+
return asyncFoldOnce(
664+
it,
665+
async (accumulator, element, index) => f(accumulator, element, index + 1),
666+
element.value
667+
);
668+
}
669+
670+
export function asyncFold1OnceFn<T>(
671+
f: (accumulator: T, element: T, index: number) => T | Promise<T>
672+
): (iterator: AsyncIteratorLike<T>) => Promise<T> {
673+
return async iterator => asyncFold1Once(iterator, f);
674+
}

0 commit comments

Comments
 (0)