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 entries in the given record and returns
|
|
|
|
* a new record containing the results.
|
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.
|
|
|
|
* @typeParam O The type of the values in the output record.
|
2024-05-06 07:51:20 +00:00
|
|
|
*
|
|
|
|
* @param record The record to map entries from.
|
|
|
|
* @param transformer The function to transform each entry.
|
|
|
|
*
|
|
|
|
* @returns A new record with all entries 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 { mapEntries } from "@std/collections/map-entries";
|
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
|
|
|
*
|
2021-07-15 21:37:53 +00:00
|
|
|
* const usersById = {
|
2022-11-25 11:40:23 +00:00
|
|
|
* "a2e": { name: "Kim", age: 22 },
|
|
|
|
* "dfe": { name: "Anna", age: 31 },
|
|
|
|
* "34b": { name: "Tim", age: 58 },
|
2024-05-06 07:51:20 +00:00
|
|
|
* };
|
|
|
|
*
|
2022-11-25 11:40:23 +00:00
|
|
|
* const agesByNames = mapEntries(usersById, ([id, { name, age }]) => [name, age]);
|
2021-07-30 14:49:46 +00:00
|
|
|
*
|
2022-11-25 11:40:23 +00:00
|
|
|
* assertEquals(
|
|
|
|
* agesByNames,
|
|
|
|
* {
|
2024-05-06 07:51:20 +00:00
|
|
|
* Kim: 22,
|
|
|
|
* Anna: 31,
|
|
|
|
* Tim: 58,
|
2022-11-25 11:40:23 +00:00
|
|
|
* },
|
|
|
|
* );
|
2021-07-15 21:37:53 +00:00
|
|
|
* ```
|
|
|
|
*/
|
|
|
|
export function mapEntries<T, O>(
|
2021-08-12 10:10:59 +00:00
|
|
|
record: Readonly<Record<string, T>>,
|
2021-08-10 08:46:14 +00:00
|
|
|
transformer: (entry: [string, T]) => [string, O],
|
2021-07-15 21:37:53 +00:00
|
|
|
): Record<string, O> {
|
2024-05-07 07:11:55 +00:00
|
|
|
const result: Record<string, O> = {};
|
2021-07-15 21:37:53 +00:00
|
|
|
const entries = Object.entries(record);
|
|
|
|
|
|
|
|
for (const entry of entries) {
|
|
|
|
const [mappedKey, mappedValue] = transformer(entry);
|
|
|
|
|
2024-05-07 07:11:55 +00:00
|
|
|
result[mappedKey] = mappedValue;
|
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
|
|
|
}
|