Skip to content
This repository was archived by the owner on Aug 24, 2025. It is now read-only.

Commit 901609a

Browse files
committed
Allow toMap* to be used with arrays, now for real.
1 parent 89b4899 commit 901609a

File tree

3 files changed

+17
-3
lines changed

3 files changed

+17
-3
lines changed

__tests__/lang/toMapBy.spec.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,4 +15,15 @@ describe("toMapBy", () => {
1515
expect(actualEntries[1]).toEqual([{ key: "b" }, 8]);
1616
expect(actualEntries[2]).toEqual([{ key: "c" }, 10]);
1717
});
18+
it("supports arrays", () => {
19+
const actual = toMapBy(
20+
[1, 2, 3],
21+
(_key, value) => value,
22+
(_key, value) => value * 2
23+
);
24+
expect(actual).toBeInstanceOf(Map);
25+
expect(actual.get(1)).toEqual(2);
26+
expect(actual.get(2)).toEqual(4);
27+
expect(actual.get(3)).toEqual(6);
28+
});
1829
});

src/lang/toMap.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ import { toMapBy } from "./toMapBy.js";
1313
* // => Map{"a": 1, "b": 4, "c": 5}
1414
*/
1515
export const toMap = <TValue>(
16-
object: Record<PropertyKey, TValue>
16+
object: Record<PropertyKey, TValue> | ArrayLike<TValue>
1717
): Map<string, TValue> =>
1818
toMapBy(
1919
object,

src/lang/toMapBy.ts

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,14 @@
99
* @param valueMapper Function mapping an object value to a map value.
1010
* @returns Map created from the object.
1111
* @example
12-
* toMap({a: 1, b: 4, c: 5}, key => { return { key }; }, value => value * 2)
12+
* toMapBy({a: 1, b: 4, c: 5}, key => { return { key }; }, value => value * 2)
1313
* // => Map{{key: "a"}: 2, {key: "b"}: 8, {key: "a"}: 10}
14+
*
15+
* toMapBy([1, 2, 3], (_key, value) => value, (_key, value) => value * 2)
16+
* // => Map{1: 2, 2: 4, 3: 6}
1417
*/
1518
export const toMapBy = <TValue, UKey, VInitialValue>(
16-
object: Record<PropertyKey, VInitialValue>,
19+
object: Record<PropertyKey, VInitialValue> | ArrayLike<VInitialValue>,
1720
keyMapper: (key: string, val: VInitialValue) => UKey,
1821
valueMapper: (key: string, value: VInitialValue) => TValue
1922
): Map<UKey, TValue> =>

0 commit comments

Comments
 (0)