mirror of
https://github.com/denoland/std.git
synced 2024-11-22 04:59:05 +00:00
d102a10235
* refactor: import from `@std/assert` * update
47 lines
1.3 KiB
TypeScript
47 lines
1.3 KiB
TypeScript
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
|
// This module is browser compatible.
|
|
|
|
/**
|
|
* Associates each string element of an array with a value returned by a selector
|
|
* function.
|
|
*
|
|
* If any of two pairs would have the same value, the latest one will be used
|
|
* (overriding the ones before it).
|
|
*
|
|
* @typeParam T The type of the values returned by the selector function.
|
|
*
|
|
* @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
|
|
* ```ts
|
|
* import { associateWith } from "@std/collections/associate-with";
|
|
* import { assertEquals } from "@std/assert";
|
|
*
|
|
* const names = ["Kim", "Lara", "Jonathan"];
|
|
*
|
|
* const namesToLength = associateWith(names, (person) => person.length);
|
|
*
|
|
* assertEquals(namesToLength, {
|
|
* "Kim": 3,
|
|
* "Lara": 4,
|
|
* "Jonathan": 8,
|
|
* });
|
|
* ```
|
|
*/
|
|
export function associateWith<T>(
|
|
array: Iterable<string>,
|
|
selector: (key: string) => T,
|
|
): Record<string, T> {
|
|
const result: Record<string, T> = {};
|
|
|
|
for (const element of array) {
|
|
result[element] = selector(element);
|
|
}
|
|
|
|
return result;
|
|
}
|