// 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).
 *
 * @template 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/assert-equals";
 *
 * 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;
}

// denoCacheMetadata={"headers":{"access-control-allow-origin":"*","x-content-type-options":"nosniff","cf-ray":"a223e6564edc7db6-LAX","etag":"\"ee47104164552e33a6ab8c44d3a9c278\"","vary":"Origin","set-cookie":"__cf_bm=j8ZH64.5_P8z_1rHBRk3oIVW25kjP16igmp0mElGt_U-1785241874.9485245-1.0.1.1-7wlnXJvNSwYW6Wr8f.KdWQZXj2p.6u86coQhZDMQX_ZTCjFgIfsrC0hecyiut2WY9fbod6oSTI2SsW0gYWpLGGygF1lnGAoR32w.taLjaX6DHrJnK_TFYbOgviQArNSx; HttpOnly; SameSite=None; Secure; Path=/; Domain=jsr.io; Expires=Tue, 28 Jul 2026 13:01:15 GMT","cache-control":"public, max-age=31536000, immutable","date":"Tue, 28 Jul 2026 12:31:15 GMT","content-type":"text/typescript","report-to":"{\"group\":\"cf-nel\",\"max_age\":604800,\"endpoints\":[{\"url\":\"https://a.nel.cloudflare.com/report/v4?s=%2BRV0%2FvdMKtLVbORTecw2fLgyB3mwc7QeOIQl2JPU5FbQ%2FURWVjrZNanUeNCGCccY31flPj2Zv1DepOU%2FpI7nK3uQYXLau%2BlEhJOP20IFAfnjxpyJXpn9R1k%3D\"}]}","cross-origin-resource-policy":"cross-origin","access-control-expose-headers":"*","x-robots-tag":"noindex","alt-svc":"h3=\":443\"; ma=86400","content-length":"1432","content-security-policy":"default-src 'none'; script-src 'none'; style-src 'none'; img-src 'none'; font-src 'none'; connect-src 'none'; frame-src 'none'; object-src 'none'; frame-ancestors 'none'; sandbox; form-action 'none';","nel":"{\"report_to\":\"cf-nel\",\"success_fraction\":0.0,\"max_age\":604800}","server":"cloudflare","x-jsr-backend":"modules"},"url":"https://jsr.io/@std/collections/0.224.2/associate_by.ts","time":1785241875}