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

/**
 * Returns the first element having the smallest value according to the provided
 * comparator or undefined if there are no elements.
 *
 * @template T The type of the elements in the array.
 *
 * @param array The array to find the minimum element in.
 * @param comparator The function to compare elements.
 *
 * @returns The first element that is the smallest value of the given function
 * or undefined if there are no elements.
 *
 * @example Basic usage
 * ```ts
 * import { minWith } from "@std/collections/min-with";
 * import { assertEquals } from "@std/assert/assert-equals";
 *
 * const people = ["Kim", "Anna", "John"];
 * const smallestName = minWith(people, (a, b) => a.length - b.length);
 *
 * assertEquals(smallestName, "Kim");
 * ```
 */
export function minWith<T>(
  array: Iterable<T>,
  comparator: (a: T, b: T) => number,
): T | undefined {
  let min: T | undefined;
  let isFirst = true;

  for (const current of array) {
    if (isFirst || comparator(current, <T> min) < 0) {
      min = current;
      isFirst = false;
    }
  }

  return min;
}

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