Skip to content

Commit 0a8b1a7

Browse files
committed
feat(mapKeyLastBy): add mapKeyLastBy function
1 parent 923e4cc commit 0a8b1a7

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

index.test.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ import {
3131
map,
3232
mapKeyBy,
3333
mapKeyFirstBy,
34+
mapKeyLastBy,
3435
maximum,
3536
maximumBy,
3637
minimum,
@@ -446,3 +447,14 @@ test("mapKeyFirstBy", async t => {
446447
t.is(map.get("odd"), "1");
447448
t.deepEqual(Array.from(map.keys()), ["odd", "even"]);
448449
});
450+
451+
test("mapKeyLastBy", async t => {
452+
const map = await mapKeyLastBy(asyncIterable([1, 3, 4, 2, 5, 6]), e => [
453+
e % 2 === 0 ? "even" : "odd",
454+
String(e)
455+
]);
456+
t.deepEqual(Array.from(map.entries()), [
457+
["odd", "5"],
458+
["even", "6"]
459+
]);
460+
});

index.ts

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1185,3 +1185,32 @@ export function mapKeyFirstByFn<TKey, TElement, TNewElement>(
11851185
}
11861186

11871187
export const asyncMapKeyFirstByFn = mapKeyFirstByFn;
1188+
1189+
export async function mapKeyLastBy<TKey, TElement, TNewElement>(
1190+
iterable: AsyncIterableLike<TElement>,
1191+
f: (
1192+
element: TElement,
1193+
index: number
1194+
) => readonly [TKey, TNewElement] | Promise<readonly [TKey, TNewElement]>
1195+
): Promise<Map<TKey, TNewElement>> {
1196+
const map = new Map<TKey, TNewElement>();
1197+
let i = 0;
1198+
for await (const element of await iterable) {
1199+
const [key, value] = await f(element, i++);
1200+
map.set(key, value);
1201+
}
1202+
return map;
1203+
}
1204+
1205+
export const asyncMapKeyLastBy = mapKeyLastBy;
1206+
1207+
export function mapKeyLastByFn<TKey, TElement, TNewElement>(
1208+
f: (
1209+
element: TElement,
1210+
index: number
1211+
) => readonly [TKey, TNewElement] | Promise<readonly [TKey, TNewElement]>
1212+
): (iterable: AsyncIterableLike<TElement>) => Promise<Map<TKey, TNewElement>> {
1213+
return async iterable => mapKeyLastBy(iterable, f);
1214+
}
1215+
1216+
export const asyncMapKeyLastByFn = mapKeyLastByFn;

0 commit comments

Comments
 (0)