Function associateWith

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

    Type Parameters

    • T

      The type of the values returned by the selector function.

    Parameters

    • array: Iterable<string, any, any>

      The array of elements to associate with values.

    • selector: ((key: string) => T)

      The selector function that returns a value for each element.

        • (key): T
        • Parameters

          • key: string

          Returns T

    Returns Record<string, T>

    An object where each element of the array is associated with a value returned by the selector function.

    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,
    });