天天看點

Lodash-add

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

/**
 * Adds two numbers.
 *
 * @since 3.4.0
 * @category Math
 * @param {number} augend The first number in an addition.
 * @param {number} addend The second number in an addition.
 * @returns {number} Returns the total.
 * @example
 *
 * add(6, 4)
 * // => 10
 */
const add = createMathOperation((augend, addend) => augend + addend, 0)

export default add
           
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.
 */
function createMathOperation(operator, defaultValue) {
  return (value, other) => {
    if (value === undefined && other === undefined) {
      return defaultValue
    }
    if (value !== undefined && other === undefined) {
      return value
    }
    if (other !== undefined && value === undefined) {
      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
           

1.createMathOperation,做校驗和轉化用

2.operator:add的參數,函數作為參數

3.add實際上就是operator

使用場景:

add自然變成用在相加

operator這種方式,在閉包中用的比較多,或者回調,比如setTimeout,callback,promise等等;

createMathOperation,去對參數做處理.

而傳回一個函數的做法,在我現階段而言,值得我去學習,這裡雖然是一個簡單的函數的校驗,但是可以用在諸多地方,去實作生成一個函數,去處理對象,事件和方法.

上一篇: lodash-at
下一篇: lodash-after