2024-01-01 21:11:32 +00:00
|
|
|
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
|
2021-09-18 18:29:29 +00:00
|
|
|
// This module is browser compatible.
|
2021-09-04 08:39:46 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Returns the first element having the largest value according to the provided
|
|
|
|
* comparator or undefined if there are no elements.
|
|
|
|
*
|
2022-11-25 11:40:23 +00:00
|
|
|
* The comparator is expected to work exactly like one passed to `Array.sort`,
|
2024-05-06 07:51:20 +00:00
|
|
|
* 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`.
|
2021-09-04 08:39:46 +00:00
|
|
|
*
|
2024-05-20 07:34:47 +00:00
|
|
|
* @typeParam T The type of the elements in the array.
|
2024-05-06 07:51:20 +00:00
|
|
|
*
|
|
|
|
* @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
|
2021-09-04 08:39:46 +00:00
|
|
|
* ```ts
|
2024-04-29 02:57:30 +00:00
|
|
|
* import { maxWith } from "@std/collections/max-with";
|
refactor(assert,async,bytes,cli,collections,crypto,csv,data-structures,datetime,dotenv,encoding,expect,fmt,front-matter,fs,html,http,ini,internal,io,json,jsonc,log,media-types,msgpack,net,path,semver,streams,testing,text,toml,ulid,url,uuid,webgpu,yaml): import from `@std/assert` (#5199)
* refactor: import from `@std/assert`
* update
2024-06-30 08:30:10 +00:00
|
|
|
* import { assertEquals } from "@std/assert";
|
2021-09-04 08:39:46 +00:00
|
|
|
*
|
|
|
|
* const people = ["Kim", "Anna", "John", "Arthur"];
|
|
|
|
* const largestName = maxWith(people, (a, b) => a.length - b.length);
|
|
|
|
*
|
|
|
|
* assertEquals(largestName, "Arthur");
|
|
|
|
* ```
|
|
|
|
*/
|
|
|
|
export function maxWith<T>(
|
2023-05-30 23:48:21 +00:00
|
|
|
array: Iterable<T>,
|
2021-09-04 08:39:46 +00:00
|
|
|
comparator: (a: T, b: T) => number,
|
|
|
|
): T | undefined {
|
2024-05-07 07:11:55 +00:00
|
|
|
let max: T | undefined;
|
2021-09-18 18:25:41 +00:00
|
|
|
let isFirst = true;
|
2021-09-04 08:39:46 +00:00
|
|
|
|
|
|
|
for (const current of array) {
|
2021-09-18 18:25:41 +00:00
|
|
|
if (isFirst || comparator(current, <T> max) > 0) {
|
2021-09-04 08:39:46 +00:00
|
|
|
max = current;
|
2021-09-18 18:25:41 +00:00
|
|
|
isFirst = false;
|
2021-09-04 08:39:46 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return max;
|
|
|
|
}
|