2023-01-03 10:47:44 +00:00
|
|
|
// Copyright 2018-2023 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
|
|
|
*
|
2022-11-25 11:40:23 +00:00
|
|
|
* @example
|
2021-07-30 14:49:46 +00:00
|
|
|
* ```ts
|
2022-06-09 19:28:39 +00:00
|
|
|
* import { mapEntries } from "https://deno.land/std@$STD_VERSION/collections/map_entries.ts";
|
2023-07-13 07:04:30 +00:00
|
|
|
* import { assertEquals } from "https://deno.land/std@$STD_VERSION/assert/assert_equals.ts";
|
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 },
|
2021-07-30 14:49:46 +00:00
|
|
|
* } as const;
|
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,
|
|
|
|
* {
|
|
|
|
* "Kim": 22,
|
|
|
|
* "Anna": 31,
|
|
|
|
* "Tim": 58,
|
|
|
|
* },
|
|
|
|
* );
|
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> {
|
|
|
|
const ret: Record<string, O> = {};
|
|
|
|
const entries = Object.entries(record);
|
|
|
|
|
|
|
|
for (const entry of entries) {
|
|
|
|
const [mappedKey, mappedValue] = transformer(entry);
|
|
|
|
|
|
|
|
ret[mappedKey] = mappedValue;
|
|
|
|
}
|
|
|
|
|
|
|
|
return ret;
|
|
|
|
}
|