Skip to content

Commit bfb4029

Browse files
committed
feat(asyncKeyFirstByOnce): add asyncKeyFirstByOnce function
1 parent 1f20126 commit bfb4029

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

index.test.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ import {
2727
asyncInitialOnce,
2828
asyncIterator,
2929
asyncKeyByOnce,
30+
asyncKeyFirstByOnce,
3031
asyncLastOnce,
3132
asyncMapOnce,
3233
asyncMaximumByOnce,
@@ -649,3 +650,13 @@ test("asyncKeyByOnce", async t => {
649650
["even", [4, 2, 6]]
650651
]);
651652
});
653+
654+
test("asyncKeyFirstByOnce", async t => {
655+
const map = await asyncKeyFirstByOnce(asyncIterator([1, 3, 4, 2, 5, 6]), e =>
656+
e % 2 === 0 ? "even" : "odd"
657+
);
658+
t.deepEqual(Array.from(map.entries()), [
659+
["odd", 1],
660+
["even", 4]
661+
]);
662+
});

index.ts

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1224,3 +1224,28 @@ export function asyncKeyByOnceFn<TKey, TElement>(
12241224
): (iterator: AsyncIteratorLike<TElement>) => Promise<Map<TKey, readonly TElement[]>> {
12251225
return async iterator => asyncKeyByOnce(iterator, f);
12261226
}
1227+
1228+
export async function asyncKeyFirstByOnce<TKey, TElement>(
1229+
iterator: AsyncIteratorLike<TElement>,
1230+
f: (element: TElement, index: number) => TKey | Promise<TKey>
1231+
): Promise<Map<TKey, TElement>> {
1232+
const it = asyncIterator(iterator);
1233+
const map = new Map<TKey, TElement>();
1234+
for (
1235+
let i = 0, element = await it.next();
1236+
element.done !== true;
1237+
++i, element = await it.next()
1238+
) {
1239+
const key = await f(element.value, i);
1240+
if (!map.has(key)) {
1241+
map.set(key, element.value);
1242+
}
1243+
}
1244+
return map;
1245+
}
1246+
1247+
export function asyncKeyFirstByOnceFn<TKey, TElement>(
1248+
f: (element: TElement, index: number) => TKey | Promise<TKey>
1249+
): (iterator: AsyncIteratorLike<TElement>) => Promise<Map<TKey, TElement>> {
1250+
return async iterator => asyncKeyFirstByOnce(iterator, f);
1251+
}

0 commit comments

Comments
 (0)