associateWith

import { associateWith } from "jsr:@ende/collections";

function

function associateWith<T>(array: Iterable<string>, selector: (key: string) => T): Record<string, T>

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).

array: Iterable<string>

The array of elements to associate with values.

selector: (key: string) => T

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

import { associateWith } from "@ende/collections/associate-with";
import { assertEquals } from "@ende/assert";

const names = ["Kim", "Lara", "Jonathan"];

const namesToLength = associateWith(names, (person) => person.length);

assertEquals(namesToLength, {
  "Kim": 3,
  "Lara": 4,
  "Jonathan": 8,
});

Source