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

/**
 * Returns all elements in the given array that produce a distinct value using
 * the given selector, preserving order by first occurrence.
 *
 * @template T The type of the elements in the input array.
 * @template D The type of the values produced by the selector function.
 *
 * @param array The array to filter for distinct elements.
 * @param selector The function to extract the value to compare for
 * distinctness.
 *
 * @returns An array of distinct elements in the input array.
 *
 * @example Basic usage
 * ```ts
 * import { distinctBy } from "@std/collections/distinct-by";
 * import { assertEquals } from "@std/assert/assert-equals";
 *
 * const names = ["Anna", "Kim", "Arnold", "Kate"];
 * const exampleNamesByFirstLetter = distinctBy(names, (name) => name.charAt(0));
 *
 * assertEquals(exampleNamesByFirstLetter, ["Anna", "Kim"]);
 * ```
 */
export function distinctBy<T, D>(
  array: Iterable<T>,
  selector: (el: T) => D,
): T[] {
  const selectedValues = new Set<D>();
  const result: T[] = [];
  for (const element of array) {
    const selected = selector(element);
    if (!selectedValues.has(selected)) {
      selectedValues.add(selected);
      result.push(element);
    }
  }
  return result;
}

// denoCacheMetadata={"headers":{"date":"Tue, 28 Jul 2026 12:31:15 GMT","cross-origin-resource-policy":"cross-origin","vary":"Origin","etag":"\"77205e8bb511aebb3130933e4a5464ae\"","content-length":"1340","x-content-type-options":"nosniff","x-jsr-backend":"modules","x-robots-tag":"noindex","set-cookie":"__cf_bm=aRP229Xc6jM3EnmeYqA64dq2d9wocQlCzATf3VpxcFs-1785241874.9507208-1.0.1.1-hnA8SxA_x6ztTX6e7v0FlveDljihK6odQO5EFUUGlMSkDM8JIDR556Fu0vIZ6Lp7pVVKSlE33Bhu_ykBuhuvkhBA0_2pZQjQAFbsEudUYQzeqvCNTSd_KZq6nVoIPpkD; HttpOnly; SameSite=None; Secure; Path=/; Domain=jsr.io; Expires=Tue, 28 Jul 2026 13:01:15 GMT","cache-control":"public, max-age=31536000, immutable","access-control-allow-origin":"*","access-control-expose-headers":"*","nel":"{\"report_to\":\"cf-nel\",\"success_fraction\":0.0,\"max_age\":604800}","cf-ray":"a223e6564ee97db6-LAX","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=vOl2buc%2FtNKqcpJ%2FzoM96KH4uhD9tp7bbU9sYlvwN0wRANQTegXX9Y8X5SYvWyMqzUcwN6F2EhqI4Au96jF%2B3eAVVih2ifisxQI8agMB5IGt1pTW742lcMM%3D\"}]}","alt-svc":"h3=\":443\"; ma=86400","server":"cloudflare","content-type":"text/typescript"},"url":"https://jsr.io/@std/collections/0.224.2/distinct_by.ts","time":1785241875}