Skip to content

Commit a677639

Browse files
committed
feat(asyncPairwiseOnce): add asyncPairwiseOnce function
1 parent 68a5b46 commit a677639

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

index.test.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ import {
3737
asyncNotEqualOnce,
3838
asyncOnlyOnce,
3939
asyncOrOnce,
40+
asyncPairwiseOnce,
4041
asyncPrefixMatchOnce,
4142
asyncPrependOnce,
4243
asyncPushOnce,
@@ -611,3 +612,15 @@ test("asyncScan1Once", async t => {
611612
[1, 3, 9]
612613
);
613614
});
615+
616+
test("asyncPairwiseOnce", async t => {
617+
t.deepEqual(await asyncToArrayOnce(asyncPairwiseOnce(asyncIterator([]))), []);
618+
t.deepEqual(await asyncToArrayOnce(asyncPairwiseOnce(asyncIterator([1]))), []);
619+
t.deepEqual(await asyncToArrayOnce(asyncPairwiseOnce(asyncIterator([1, 2]))), [[1, 2]]);
620+
t.deepEqual(await asyncToArrayOnce(asyncPairwiseOnce(asyncIterator([1, 2, 3, 4, 5]))), [
621+
[1, 2],
622+
[2, 3],
623+
[3, 4],
624+
[4, 5]
625+
]);
626+
});

index.ts

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1139,3 +1139,35 @@ export function asyncScan1OnceFn<T>(
11391139
): (iterator: AsyncIteratorLike<T>) => AsyncIterator<T> {
11401140
return iterator => asyncScan1Once(iterator, f);
11411141
}
1142+
1143+
export function asyncPairwiseOnce<T>(
1144+
iterator: AsyncIteratorLike<T>
1145+
): AsyncIterator<readonly [T, T]> {
1146+
const it = asyncIterator(iterator);
1147+
const before = async (): Promise<IteratorResult<readonly [T, T]>> => {
1148+
const element = await it.next();
1149+
if (element.done === true) {
1150+
next = after;
1151+
return after();
1152+
} else {
1153+
next = during(element.value);
1154+
return next();
1155+
}
1156+
};
1157+
const during = (previous: T) => async (): Promise<IteratorResult<readonly [T, T]>> => {
1158+
const element = await it.next();
1159+
if (element.done === true) {
1160+
next = after;
1161+
return after();
1162+
} else {
1163+
next = during(element.value);
1164+
return {value: [previous, element.value]};
1165+
}
1166+
};
1167+
const after = async (): Promise<IteratorResult<readonly [T, T]>> => ({
1168+
done: true,
1169+
value: undefined
1170+
});
1171+
let next = before;
1172+
return {next: async () => next()};
1173+
}

0 commit comments

Comments
 (0)