All files / collections / associate_with.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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x3
x3
x3
 
x10
 
x10
x29
x29
 
x10
x10












































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