std/collections/associate_by.ts

51 lines
1.4 KiB
TypeScript

// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
// This module is browser compatible.
/**
* Creates a record by associating each element of the input array with a key
* generated by the selector function.
*
* If the selector produces the same key for multiple elements, the latest one
* will be used (overriding the ones before it).
*
* @typeParam T Type of the elements in the input array.
*
* @param array The array to transform.
* @param selector The function to extract the key from each element.
*
* @returns A record with the keys produced by the selector and the elements as
* values.
*
* @example Basic usage
* ```ts
* import { associateBy } from "@std/collections/associate-by";
* import { assertEquals } from "@std/assert";
*
* const users = [
* { id: "a2e", userName: "Anna" },
* { id: "5f8", userName: "Arnold" },
* { id: "d2c", userName: "Kim" },
* ];
*
* const usersById = associateBy(users, (user) => user.id);
*
* assertEquals(usersById, {
* "a2e": { id: "a2e", userName: "Anna" },
* "5f8": { id: "5f8", userName: "Arnold" },
* "d2c": { id: "d2c", userName: "Kim" },
* });
* ```
*/
export function associateBy<T>(
array: Iterable<T>,
selector: (el: T) => string,
): Record<string, T> {
const result: Record<string, T> = {};
for (const element of array) {
result[selector(element)] = element;
}
return result;
}