Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 | 1x 1x 1x 3x 3x 5x 4x 1x | import { isLessThan, Comparator } from "@benneq/comparator";
import { isUndefined } from "@benneq/object";
import { reduce } from "./reduce";
/**
* Get the maximum element from an {@link Iterable} by comparing its elements
* using a {@link Comparator}.
*
* @example
* Find max number in Array
* ```ts
* const findMaxNumber = max(numberComparator);
* const maxNumber = findMaxNumber([1,2,3]);
* console.log(maxNumber); // 3
* ```
*
* @typeParam T - the {@link Iterable} value type
* @param comparator - the {@link Comparator} to use
* @returns the maximum element, or `undefined` if the {@link Iterable} is empty
*/
export const max = <T>(
comparator: Comparator<T>,
maxValueIsLess = isLessThan(comparator)
): ((iterable: Iterable<T>) => T | undefined) => {
return reduce<T, T | undefined>((maxValue, value) => {
if (isUndefined(maxValue) || maxValueIsLess(maxValue, value)) {
return value;
} else {
return maxValue;
}
}, undefined);
};
|