mirror of
https://github.com/whoisclebs/lodash.git
synced 2026-01-31 07:17:50 +00:00
42 lines
1.0 KiB
JavaScript
42 lines
1.0 KiB
JavaScript
import isSymbol from './isSymbol.js'
|
|
|
|
/**
|
|
* This method is like `max` except that it accepts `iteratee` which is
|
|
* invoked for each element in `array` to generate the criterion by which
|
|
* the value is ranked. The iteratee is invoked with one argument: (value).
|
|
*
|
|
* @since 4.0.0
|
|
* @category Math
|
|
* @param {Array} array The array to iterate over.
|
|
* @param {Function} iteratee The iteratee invoked per element.
|
|
* @returns {*} Returns the maximum value.
|
|
* @example
|
|
*
|
|
* const objects = [{ 'n': 1 }, { 'n': 2 }]
|
|
*
|
|
* maxBy(objects, ({ n }) => n)
|
|
* // => { 'n': 2 }
|
|
*/
|
|
function maxBy(array, iteratee) {
|
|
let result
|
|
let index = -1
|
|
const length = array == null ? 0 : array.length
|
|
|
|
while (++index < length) {
|
|
let computed
|
|
const value = array[index]
|
|
const current = iteratee(value)
|
|
|
|
if (current != null && (computed === undefined
|
|
? (current === current && !isSymbol(current))
|
|
: (current > computed)
|
|
)) {
|
|
computed = current
|
|
result = value
|
|
}
|
|
}
|
|
return result
|
|
}
|
|
|
|
export default maxBy
|