Skip to content

Commit 68a5b46

Browse files
committed
feat(asyncScan1Once): add asyncScan1Once function
1 parent 70115ec commit 68a5b46

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

index.test.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ import {
4242
asyncPushOnce,
4343
asyncRemoveFirstOnce,
4444
asyncRemoveOnce,
45+
asyncScan1Once,
4546
asyncScanOnce,
4647
asyncSliceOnce,
4748
asyncSumOnce,
@@ -603,3 +604,10 @@ test("asyncScanOnce", async t => {
603604
["_ 0 a", "_ 0 a 1 b", "_ 0 a 1 b 2 c"]
604605
);
605606
});
607+
608+
test("asyncScan1Once", async t => {
609+
t.deepEqual(
610+
await asyncToArrayOnce(asyncScan1Once(asyncIterator([1, 2, 3]), (a, e, i) => a + e * i)),
611+
[1, 3, 9]
612+
);
613+
});

index.ts

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1101,3 +1101,41 @@ export function asyncScanOnceFn<T, U>(
11011101
): (iterator: AsyncIteratorLike<T>) => AsyncIterator<U> {
11021102
return iterator => asyncScanOnce(iterator, f, initial);
11031103
}
1104+
1105+
export function asyncScan1Once<T>(
1106+
iterator: AsyncIteratorLike<T>,
1107+
f: (accumulator: T, element: T, index: number) => T | Promise<T>
1108+
): AsyncIterator<T> {
1109+
const it = asyncIterator(iterator);
1110+
let i = 1;
1111+
const first = async (): Promise<IteratorResult<T>> => {
1112+
const element = await it.next();
1113+
if (element.done === true) {
1114+
next = after;
1115+
return after();
1116+
} else {
1117+
next = during(element.value);
1118+
return {value: element.value};
1119+
}
1120+
};
1121+
const during = (accumulator: T) => async (): Promise<IteratorResult<T>> => {
1122+
const element = await it.next();
1123+
if (element.done === true) {
1124+
next = after;
1125+
return after();
1126+
} else {
1127+
const value = await f(accumulator, element.value, i++);
1128+
next = during(value);
1129+
return {value};
1130+
}
1131+
};
1132+
const after = async (): Promise<IteratorResult<T>> => ({done: true, value: undefined});
1133+
let next = first;
1134+
return {next: async () => next()};
1135+
}
1136+
1137+
export function asyncScan1OnceFn<T>(
1138+
f: (accumulator: T, element: T, index: number) => T | Promise<T>
1139+
): (iterator: AsyncIteratorLike<T>) => AsyncIterator<T> {
1140+
return iterator => asyncScan1Once(iterator, f);
1141+
}

0 commit comments

Comments
 (0)