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-09-12 13:49:15 +00:00
|
|
|
|
|
|
|
/**
|
2024-05-19 14:02:09 +00:00
|
|
|
* Associates each string element of an array with a value returned by a selector
|
2024-05-06 07:51:20 +00:00
|
|
|
* function.
|
2021-09-12 13:49:15 +00:00
|
|
|
*
|
2024-05-19 14:02:09 +00:00
|
|
|
* If any of two pairs would have the same value, the latest one will be used
|
2024-05-06 07:51:20 +00:00
|
|
|
* (overriding the ones before it).
|
|
|
|
*
|
2024-05-20 07:34:47 +00:00
|
|
|
* @typeParam T The type of the values returned by the selector function.
|
2024-05-06 07:51:20 +00:00
|
|
|
*
|
|
|
|
* @param array The array of elements to associate with values.
|
|
|
|
* @param selector The selector function that returns a value for each element.
|
|
|
|
*
|
|
|
|
* @returns An object where each element of the array is associated with a value
|
|
|
|
* returned by the selector function.
|
|
|
|
*
|
|
|
|
* @example Basic usage
|
2021-09-12 13:49:15 +00:00
|
|
|
* ```ts
|
2024-04-29 02:57:30 +00:00
|
|
|
* import { associateWith } from "@std/collections/associate-with";
|
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-09-12 13:49:15 +00:00
|
|
|
*
|
2022-11-25 11:40:23 +00:00
|
|
|
* const names = ["Kim", "Lara", "Jonathan"];
|
2024-05-06 07:51:20 +00:00
|
|
|
*
|
|
|
|
* const namesToLength = associateWith(names, (person) => person.length);
|
2021-09-12 13:49:15 +00:00
|
|
|
*
|
|
|
|
* assertEquals(namesToLength, {
|
2022-11-25 11:40:23 +00:00
|
|
|
* "Kim": 3,
|
|
|
|
* "Lara": 4,
|
|
|
|
* "Jonathan": 8,
|
|
|
|
* });
|
2021-09-12 13:49:15 +00:00
|
|
|
* ```
|
|
|
|
*/
|
|
|
|
export function associateWith<T>(
|
2023-05-30 23:48:21 +00:00
|
|
|
array: Iterable<string>,
|
2021-09-12 13:49:15 +00:00
|
|
|
selector: (key: string) => T,
|
|
|
|
): Record<string, T> {
|
2024-05-07 07:11:55 +00:00
|
|
|
const result: Record<string, T> = {};
|
2021-09-12 13:49:15 +00:00
|
|
|
|
|
|
|
for (const element of array) {
|
2024-05-07 07:11:55 +00:00
|
|
|
result[element] = selector(element);
|
2021-09-12 13:49:15 +00:00
|
|
|
}
|
|
|
|
|
2024-05-07 07:11:55 +00:00
|
|
|
return result;
|
2021-09-12 13:49:15 +00:00
|
|
|
}
|