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

/**
 * Returns the first element having the largest value according to the provided
 * comparator or undefined if there are no elements.
 *
 * The comparator is expected to work exactly like one passed to `Array.sort`,
 * which means that `comparator(a, b)` should return a negative number if
 * `a < b`, a positive number if `a > b` and `0` if `a === b`.
 *
 * @template T The type of the elements in the array.
 *
 * @param array The array to find the maximum element in.
 * @param comparator The function to compare elements.
 *
 * @returns The first element that is the largest value of the given function or
 * undefined if there are no elements.
 *
 * @example Basic usage
 * ```ts
 * import { maxWith } from "@std/collections/max-with";
 * import { assertEquals } from "@std/assert/assert-equals";
 *
 * const people = ["Kim", "Anna", "John", "Arthur"];
 * const largestName = maxWith(people, (a, b) => a.length - b.length);
 *
 * assertEquals(largestName, "Arthur");
 * ```
 */
export function maxWith<T>(
  array: Iterable<T>,
  comparator: (a: T, b: T) => number,
): T | undefined {
  let max: T | undefined;
  let isFirst = true;

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

  return max;
}

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