/
max_with.ts
39 lines (36 loc) · 1.15 KB
/
max_with.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// Copyright 2018-2021 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`.
*
* Example:
*
* ```ts
* import { maxWith } from "https://deno.land/std@$STD_VERSION/collections/mod.ts";
* import { assertEquals } from "https://deno.land/std@$STD_VERSION/testing/asserts.ts";
*
* const people = ["Kim", "Anna", "John", "Arthur"];
* const largestName = maxWith(people, (a, b) => a.length - b.length);
*
* assertEquals(largestName, "Arthur");
* ```
*/
export function maxWith<T>(
array: readonly T[],
comparator: (a: T, b: T) => number,
): T | undefined {
let max: T | undefined = undefined;
let isFirst = true;
for (const current of array) {
if (isFirst || comparator(current, <T> max) > 0) {
max = current;
isFirst = false;
}
}
return max;
}