计算数组中的最大值,如果数组是空的或者是非数组则返回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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值