All files / collections / associate_by.ts

100.00% Branches 1/1
100.00% Lines 9/9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x3
x3
x3
 
x12
 
x12
x41
x41
 
x12
x12
















































// Copyright 2018-2025 the Deno authors. 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;
}