Skip to content

Commit 045cbc9

Browse files
committed
feat(keyLastBy): add keyLastBy function
1 parent 89688a0 commit 045cbc9

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

index.test.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import {
2424
index,
2525
indexOf,
2626
initial,
27+
keyLastBy,
2728
last,
2829
map,
2930
maximum,
@@ -384,3 +385,13 @@ test("zip", async t => {
384385
[3, 4]
385386
]);
386387
});
388+
389+
test("keyLastBy", async t => {
390+
const map = await keyLastBy(asyncIterable([1, 3, 4, 2, 5, 6]), e =>
391+
e % 2 === 0 ? "even" : "odd"
392+
);
393+
t.deepEqual(Array.from(map.entries()), [
394+
["odd", 5],
395+
["even", 6]
396+
]);
397+
});

index.ts

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1016,3 +1016,25 @@ export function zipFn<T, U>(
10161016
}
10171017

10181018
export const asyncZipFn = zipFn;
1019+
1020+
export async function keyLastBy<TKey, TElement>(
1021+
iterable: AsyncIterableLike<TElement>,
1022+
f: (element: TElement, index: number) => TKey
1023+
): Promise<Map<TKey, TElement>> {
1024+
const map = new Map<TKey, TElement>();
1025+
let i = 0;
1026+
for await (const element of await iterable) {
1027+
map.set(f(element, i++), element);
1028+
}
1029+
return map;
1030+
}
1031+
1032+
export const asyncKeyLastBy = keyLastBy;
1033+
1034+
export function keyLastByFn<TKey, TElement>(
1035+
f: (element: TElement, index: number) => TKey
1036+
): (iterable: AsyncIterableLike<TElement>) => Promise<Map<TKey, TElement>> {
1037+
return async iterable => keyLastBy(iterable, f);
1038+
}
1039+
1040+
export const asyncKeyLastByFn = keyLastByFn;

0 commit comments

Comments
 (0)