-
Notifications
You must be signed in to change notification settings - Fork 604
/
map_keys.ts
38 lines (34 loc) · 949 Bytes
/
map_keys.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
/**
* Applies the given transformer to all keys in the given record's entries and returns a new record containing the
* transformed entries.
*
* If the transformed entries contain the same key multiple times, only the last one will appear in the returned record.
*
* Example:
*
* ```ts
* import { mapKeys } from "./map_keys.ts";
* import { assertEquals } from "../testing/asserts.ts";
*
* const counts = { a: 5, b: 3, c: 8 }
*
* assertEquals(mapKeys(counts, it => it.toUpperCase()), {
* A: 5,
* B: 3,
* C: 8,
* })
* ```
*/
export function mapKeys<T>(
record: Record<string, T>,
transformer: (key: string) => string,
): Record<string, T> {
const ret: Record<string, T> = {};
const keys = Object.keys(record);
for (const key of keys) {
const mappedKey = transformer(key);
ret[mappedKey] = record[key];
}
return ret;
}