Skip to content

Commit b0fbfd0

Browse files
committed
feat(pairwise): add pairwise function
1 parent ae14212 commit b0fbfd0

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

index.test.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ import {
4040
notEmpty,
4141
only,
4242
or,
43+
pairwise,
4344
prefixMatch,
4445
prepend,
4546
product,
@@ -394,6 +395,18 @@ test("scan1", async t => {
394395
t.deepEqual(await toArray(scan1(asyncIterable([1, 2, 3]), (a, e, i) => a + e * i)), [1, 3, 9]);
395396
});
396397

398+
test("pairwise", async t => {
399+
t.deepEqual(await toArray(pairwise(asyncIterable([]))), []);
400+
t.deepEqual(await toArray(pairwise(asyncIterable([1]))), []);
401+
t.deepEqual(await toArray(pairwise(asyncIterable([1, 2]))), [[1, 2]]);
402+
t.deepEqual(await toArray(pairwise(asyncIterable([1, 2, 3, 4, 5]))), [
403+
[1, 2],
404+
[2, 3],
405+
[3, 4],
406+
[4, 5]
407+
]);
408+
});
409+
397410
test("zip", async t => {
398411
t.deepEqual(await toArray(zip(asyncIterable([1, 2, 3]), asyncIterable([6, 5, 4, 3, 2, 1]))), [
399412
[1, 6],

index.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1028,6 +1028,22 @@ export function scan1Fn<T>(
10281028
return iterable => scan1(iterable, f);
10291029
}
10301030

1031+
export async function* pairwise<T>(iterable: AsyncIterableLike<T>): AsyncIterable<readonly [T, T]> {
1032+
const iterator = asyncIterator(iterable);
1033+
let prev = await iterator.next();
1034+
1035+
if (prev.done === true) {
1036+
return;
1037+
}
1038+
1039+
let element = await iterator.next();
1040+
while (element.done !== true) {
1041+
yield [prev.value, element.value];
1042+
prev = element;
1043+
element = await iterator.next();
1044+
}
1045+
}
1046+
10311047
export async function* zip<T, U>(
10321048
a: AsyncIterableLike<T>,
10331049
b: AsyncIterableLike<U>

0 commit comments

Comments
 (0)