_.subtract(minuend, subtrahend)

185

_.subtract(minuend, subtrahend)
_.subtract将两个数字相减

参数

minuend (number): 被减数
subtrahend (number): 减数

返回值

(number): 返回差

例子

 

_.subtract(6, 4);
// => 2

 

源代码

import createMathOperation from './.internal/createMathOperation.js'

/**
 * Subtract two numbers.
 *
 * @since 4.0.0
 * @category Math
 * @param {number} minuend The first number in a subtraction.
 * @param {number} subtrahend The second number in a subtraction.
 * @returns {number} Returns the difference.
 * @example
 *
 * subtract(6, 4)
 * // => 2
 */
//将两个数字相减
const subtract = createMathOperation((minuend, subtrahend) => minuend - subtrahend, 0)

export default subtract
createMathOperation
import baseToNumber from './baseToNumber.js'
import baseToString from './baseToString.js'

/**
 * Creates a function that performs a mathematical operation on two values.
 *
 * @private
 * @param {Function} operator The function to perform the operation.
 * @param {number} [defaultValue] The value used for `undefined` arguments.
 * @returns {Function} Returns the new mathematical operation function.
 */
//createMathOperation方法用于创建一个对两个值做数学操作的方法,第一个参数是对两个值所做的操作,第二个参数是对undefined值所使用的替换默认值
function createMathOperation(operator, defaultValue) {
  return (value, other) => {//返回这个数学操作方法
    if (value === undefined && other === undefined) {
      //如果两个操作值都是undefined,返回默认值
      return defaultValue
    }
    if (value !== undefined && other === undefined) {
      //如果value不是undefined而other是undefined,返回value
      return value
    }
    if (other !== undefined && value === undefined) {
      //如果other不是undefined而value是undefined,返回other
      return other
    }
    if (typeof value == 'string' || typeof other == 'string') {
      //两个值中某一个是字符串,则都转成字符串
      value = baseToString(value)
      other = baseToString(other)
    }
    else {//否则转成数字
      value = baseToNumber(value)
      other = baseToNumber(other)
    }
    return operator(value, other)//返回操作结果
  }
}

export default createMathOperation

 

posted @ 2019-04-24 10:12  hahazexia  阅读(1323)  评论(0)    收藏  举报