// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
// This module is browser compatible.

/**
 * Associates each element of an array with a value returned by a selector
 * function.
 *
 * If any of two pairs would have the same value the latest on will be used
 * (overriding the ones before it).
 *
 * @template 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/assert-equals";
 *
 * 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;
}

// denoCacheMetadata={"headers":{"cache-control":"public, max-age=31536000, immutable","x-content-type-options":"nosniff","access-control-expose-headers":"*","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';","report-to":"{\"group\":\"cf-nel\",\"max_age\":604800,\"endpoints\":[{\"url\":\"https://a.nel.cloudflare.com/report/v4?s=zt7hklOmjxiq1x8Mty%2B9TUXpc1F9izA95EIitdM71WcFZRoiKREHkfWm1sEMaliEft4qVvu787LZaBMcReblWF96Ul32L2MY21pAV%2FiuqhMVNyLQFvkqihI%3D\"}]}","cf-ray":"a223e6564edd7db6-LAX","alt-svc":"h3=\":443\"; ma=86400","etag":"\"e96154b1faa56ba2cf69a10f598d4a47\"","server":"cloudflare","content-length":"1317","access-control-allow-origin":"*","x-jsr-backend":"modules","vary":"Origin","x-robots-tag":"noindex","nel":"{\"report_to\":\"cf-nel\",\"success_fraction\":0.0,\"max_age\":604800}","date":"Tue, 28 Jul 2026 12:31:15 GMT","set-cookie":"__cf_bm=wh7kNtw6_m1k2TEEsCY2bKxEnnV8_bMmW8NMNXiOYJA-1785241874.948844-1.0.1.1-V9W8QIszTCUcO1YiwG1LMQRRWczgDTtk2AWnuWqxE_FOD5ePkMNWHpv4QjKp3palAVkN4pgC89R7QDA8yMCZtXYaYwoKHHr36ZSDct7YONyOYW7IbIrgPlaQJEFSsnwY; HttpOnly; SameSite=None; Secure; Path=/; Domain=jsr.io; Expires=Tue, 28 Jul 2026 13:01:15 GMT","content-type":"text/typescript","cross-origin-resource-policy":"cross-origin"},"url":"https://jsr.io/@std/collections/0.224.2/associate_with.ts","time":1785241875}