Skip to content

Commit 1f20126

Browse files
committed
feat(asyncKeyByOnce): add asyncKeyByOnce function
1 parent 4a9acc0 commit 1f20126

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

index.test.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ import {
2626
asyncIndexOnce,
2727
asyncInitialOnce,
2828
asyncIterator,
29+
asyncKeyByOnce,
2930
asyncLastOnce,
3031
asyncMapOnce,
3132
asyncMaximumByOnce,
@@ -638,3 +639,13 @@ test("asyncZipOnce", async t => {
638639
]
639640
);
640641
});
642+
643+
test("asyncKeyByOnce", async t => {
644+
const map = await asyncKeyByOnce(asyncIterator([1, 3, 4, 2, 5, 6]), e =>
645+
e % 2 === 0 ? "even" : "odd"
646+
);
647+
t.deepEqual(Array.from(map.entries()), [
648+
["odd", [1, 3, 5]],
649+
["even", [4, 2, 6]]
650+
]);
651+
});

index.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1200,3 +1200,27 @@ export function asyncZipOnceFn<T, U>(
12001200
): (a: AsyncIteratorLike<T>) => AsyncIterator<readonly [T, U]> {
12011201
return a => asyncZipOnce(a, b);
12021202
}
1203+
1204+
export async function asyncKeyByOnce<TKey, TElement>(
1205+
iterator: AsyncIteratorLike<TElement>,
1206+
f: (element: TElement, index: number) => TKey | Promise<TKey>
1207+
): Promise<Map<TKey, readonly TElement[]>> {
1208+
const it = asyncIterator(iterator);
1209+
const map = new Map<TKey, TElement[]>();
1210+
for (
1211+
let i = 0, element = await it.next();
1212+
element.done !== true;
1213+
++i, element = await it.next()
1214+
) {
1215+
const key = await f(element.value, i);
1216+
const entries = map.get(key) ?? [];
1217+
map.set(key, [...entries, element.value]);
1218+
}
1219+
return map;
1220+
}
1221+
1222+
export function asyncKeyByOnceFn<TKey, TElement>(
1223+
f: (element: TElement, index: number) => TKey | Promise<TKey>
1224+
): (iterator: AsyncIteratorLike<TElement>) => Promise<Map<TKey, readonly TElement[]>> {
1225+
return async iterator => asyncKeyByOnce(iterator, f);
1226+
}

0 commit comments

Comments
 (0)