计算数组中的最大值,如果数组是空的或者是非数组则返回undefined

/**
 * 计算array中的最大值,如果array是空的或者是非数组则返回undefined
 * computes the maximum value of `array`. If `array` is empty or falsey
 * `undefined` is returned.
 * @param {Array} array The array to iterate over
 * @returns {*} Returns the maximum value
 * @example
 * max([4, 2, 8, 6]);
 * // => 8
 * max([])
 * // => undefined
 */

import baseExtremum from "./baseExtremum"

function identity(value) {
  return value
}

function baseGt(value, other) {
  return value > other
}

function max(array) {
  return array && array.length
    ? baseExtremum(array, identity, baseGt)
    : undefined
}

export default max
/**
 * The base implementation of methods like `max` and `min` which accepts a `comparator`
 * to determine the extremum value
 * @param {Array} array The array to iterate over
 * @param {Function} iteratee The iteratee invoked per iteration
 * @param {Function} comparator The comparator used to compare values
 * @returns {*} Returns the extremum value
 */

function baseExtremum(array, iteratee, comparator) {
  var index = -1,
    length = array.length,
    result = undefined,
    computed = undefined

  while (++index < length) {
    var value = array[index],
      current = iteratee(value)

    if (
      current != null &&
      (computed === undefined
        ? current === current
        : comparator(current, computed))
    ) {
      computed = current
      result = value
    }
  }

  return result
}

export default baseExtremum

 

你可能感兴趣的:(lodash)