UNPKG

818 BPlain TextView Raw
1import each from './each';
2import isArray from './is-array';
3import isFunction from './is-function';
4/**
5 * @param {Array} arr The array to iterate over.
6 * @param {Function} [fn] The iteratee invoked per element.
7 * @return {*} Returns the maximum value.
8 * @example
9 *
10 * var objects = [{ 'n': 1 }, { 'n': 2 }];
11 *
12 * maxBy(objects, function(o) { return o.n; });
13 * // => { 'n': 2 }
14 *
15 * maxBy(objects, 'n');
16 * // => { 'n': 2 }
17 */
18export default <T>(arr: T[], fn: ((v: T) => number) | string): T | undefined => {
19 if (!isArray(arr)) {
20 return undefined;
21 }
22
23 let maxItem;
24 let max = -Infinity;
25
26 for (let i = 0; i < arr.length; i++) {
27 const item = arr[i];
28 const v = isFunction(fn) ? fn(item) : item[fn];
29
30 if (v > max) {
31 maxItem = item;
32 max = v;
33 }
34 }
35
36 return maxItem;
37};