# ❓ 实现 (5).add(3).minus(2) 功能

简单版

Number.prototype.add = function(num) {
  return this + num
}

Number.prototype.minus = function(num) {
  return this - num
}
;(5).add(3).minus(2)
1
2
3
4
5
6
7
8

全面版

Number.MAX_SAFE_DIGITS = Number.MAX_SAFE_INTEGER.toString().length - 2
Number.prototype.digits = function() {
  let result = (
    this.valueOf()
      .toString()
      .split('.')[1] || ''
  ).length
  return result > Number.MAX_SAFE_DIGITS ? Number.MAX_SAFE_DIGITS : result
}
Number.prototype.add = function(i = 0) {
  if (typeof i !== 'number') {
    throw new Error('请输入正确的数字')
  }
  const v = this.valueOf()
  const thisDigits = this.digits()
  const iDigits = i.digits()
  const baseNum = Math.pow(10, Math.max(thisDigits, iDigits))
  const result = (v * baseNum + i * baseNum) / baseNum
  if (result > 0) {
    return result > Number.MAX_SAFE_INTEGER ? Number.MAX_SAFE_INTEGER : result
  } else {
    return result < Number.MIN_SAFE_INTEGER ? Number.MIN_SAFE_INTEGER : result
  }
}
Number.prototype.minus = function(i = 0) {
  if (typeof i !== 'number') {
    throw new Error('请输入正确的数字')
  }
  const v = this.valueOf()
  const thisDigits = this.digits()
  const iDigits = i.digits()
  const baseNum = Math.pow(10, Math.max(thisDigits, iDigits))
  const result = (v * baseNum - i * baseNum) / baseNum
  if (result > 0) {
    return result > Number.MAX_SAFE_INTEGER ? Number.MAX_SAFE_INTEGER : result
  } else {
    return result < Number.MIN_SAFE_INTEGER ? Number.MIN_SAFE_INTEGER : result
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39

JS 的经典的浮点数陷阱