lodash源码学习之Math

本文深入剖析lodash库中Math相关的函数,包括add、ceil、divide、floor等,详细解释了每个函数的实现原理、用途及源码解读,帮助读者理解lodash中数值操作的实现方式。
摘要由CSDN通过智能技术生成

一、lodash版本:4.17.5

二、函数:

1、add

1)含义:两个月相加

2) 例子。

const _ = require('lodash’);

console.log(_.add(10, 20));// 输出:30

3) 源码解读。

源码:

const INFINITY = 1 / 0

const symbolProto = Symbol ? Symbol.prototype : undefined

const symbolToString = symbolProto ? symbolProto.toString : undefined

const add = createMathOperation((augend, addend) => augend + addend, 0)

function baseToNumber(value) {

  if (typeof value == 'number') {

    return value

  }

  if (isSymbol(value)) {

    return NAN

  }

  return +value

}



function isSymbol(value) {

  const type = typeof value

  return type == 'symbol' || (type == 'object' && value != null && getTag(value) == '[object Symbol]')

}

 

解读:

(1)在createMathOperation函数中,前三个if判断value和other是否为空,如果都为空就返回defaultValue(也就是0)。如果有一个为空,就返回另外一个不为空的值。接着判断value和other是否字符型,如果是,则调用baseToNumber。核心源代码,如下所示:

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)

  }

}

实例如下:

const _ = require('lodash');
console.log(_.add(undefined, undefined)) // 输出:0
console.log(_.add(1, '')); // 输出:1

    

(2)在baseToString中,如果传入的参数是字符串,那么直接返回该字符串进行计算。核心代码,如下所示:

  if (ty
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值