2024-01-01 21:11:32 +00:00
|
|
|
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
2021-09-18 18:29:29 +00:00
|
|
|
// This module is browser compatible.
|
2021-07-15 21:37:53 +00:00
|
|
|
|
|
|
|
/**
|
2022-11-25 11:40:23 +00:00
|
|
|
* Applies the given transformer to all keys in the given record's entries and
|
|
|
|
* returns a new record containing the transformed entries.
|
2021-07-15 21:37:53 +00:00
|
|
|
*
|
2022-11-25 11:40:23 +00:00
|
|
|
* If the transformed entries contain the same key multiple times, only the last
|
|
|
|
* one will appear in the returned record.
|
2021-07-15 21:37:53 +00:00
|
|
|
*
|
2024-05-20 07:34:47 +00:00
|
|
|
* @typeParam T The type of the values in the input record.
|
2024-05-06 07:51:20 +00:00
|
|
|
*
|
|
|
|
* @param record The record to map keys from.
|
|
|
|
* @param transformer The function to transform each key.
|
|
|
|
*
|
|
|
|
* @returns A new record with all keys transformed by the given transformer.
|
|
|
|
*
|
|
|
|
* @example Basic usage
|
2021-07-30 14:49:46 +00:00
|
|
|
* ```ts
|
2024-04-29 02:57:30 +00:00
|
|
|
* import { mapKeys } from "@std/collections/map-keys";
|
refactor(assert,async,bytes,cli,collections,crypto,csv,data-structures,datetime,dotenv,encoding,expect,fmt,front-matter,fs,html,http,ini,internal,io,json,jsonc,log,media-types,msgpack,net,path,semver,streams,testing,text,toml,ulid,url,uuid,webgpu,yaml): import from `@std/assert` (#5199)
* refactor: import from `@std/assert`
* update
2024-06-30 08:30:10 +00:00
|
|
|
* import { assertEquals } from "@std/assert";
|
2021-07-30 14:49:46 +00:00
|
|
|
*
|
2022-11-25 11:40:23 +00:00
|
|
|
* const counts = { a: 5, b: 3, c: 8 };
|
2021-07-15 21:37:53 +00:00
|
|
|
*
|
2022-11-25 11:40:23 +00:00
|
|
|
* assertEquals(
|
2024-05-06 07:51:20 +00:00
|
|
|
* mapKeys(counts, (key) => key.toUpperCase()),
|
2022-11-25 11:40:23 +00:00
|
|
|
* {
|
2021-07-15 21:37:53 +00:00
|
|
|
* A: 5,
|
|
|
|
* B: 3,
|
|
|
|
* C: 8,
|
2022-11-25 11:40:23 +00:00
|
|
|
* },
|
|
|
|
* );
|
2021-07-15 21:37:53 +00:00
|
|
|
* ```
|
|
|
|
*/
|
|
|
|
export function mapKeys<T>(
|
2021-08-12 10:10:59 +00:00
|
|
|
record: Readonly<Record<string, T>>,
|
2021-08-10 08:46:14 +00:00
|
|
|
transformer: (key: string) => string,
|
2021-07-15 21:37:53 +00:00
|
|
|
): Record<string, T> {
|
2024-05-07 07:11:55 +00:00
|
|
|
const result: Record<string, T> = {};
|
2021-07-15 21:37:53 +00:00
|
|
|
|
2024-02-02 06:01:54 +00:00
|
|
|
for (const [key, value] of Object.entries(record)) {
|
2021-07-15 21:37:53 +00:00
|
|
|
const mappedKey = transformer(key);
|
2024-05-07 07:11:55 +00:00
|
|
|
result[mappedKey] = value;
|
2021-07-15 21:37:53 +00:00
|
|
|
}
|
|
|
|
|
2024-05-07 07:11:55 +00:00
|
|
|
return result;
|
2021-07-15 21:37:53 +00:00
|
|
|
}
|