2021-07-15 21:37:53 +00:00
|
|
|
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Applies the given transformer to all entries in the given record and returns a new record containing the results
|
|
|
|
*
|
|
|
|
* Example:
|
|
|
|
*
|
2021-07-30 14:49:46 +00:00
|
|
|
* ```ts
|
2021-09-13 05:46:42 +00:00
|
|
|
* import { mapEntries } from "https://deno.land/std@$STD_VERSION/collections/mod.ts";
|
|
|
|
* import { assertEquals } from "https://deno.land/std@$STD_VERSION/testing/asserts.ts";
|
2021-07-30 14:49:46 +00:00
|
|
|
*
|
2021-07-15 21:37:53 +00:00
|
|
|
* const usersById = {
|
|
|
|
* '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;
|
|
|
|
*
|
2021-07-15 21:37:53 +00:00
|
|
|
* const agesByNames = mapEntries(usersById,
|
|
|
|
* ([ id, { name, age } ]) => [ name, age ],
|
|
|
|
* )
|
|
|
|
*
|
2021-08-10 08:46:14 +00:00
|
|
|
* assertEquals(agesByNames, {
|
2021-07-15 21:37:53 +00:00
|
|
|
* 'Kim': 22,
|
|
|
|
* 'Anna': 31,
|
|
|
|
* 'Tim': 58,
|
|
|
|
* })
|
|
|
|
* ```
|
|
|
|
*/
|
|
|
|
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;
|
|
|
|
}
|