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

1,302 阅读1分钟
(5).add(3).minus(2) 
    // 6

实现:

    Number.prototype.add = function (value) {
        let  number = parseFloat(value);
        if (typeof number !== 'number' || Number.isNaN(number)) {
            throw new Error('请输入数字或者数字字符串~');
        };
        return this + number;
    };
    Number.prototype.minus = function (value) {
        let  number = parseFloat(value);
        if (typeof number !== 'number' || Number.isNaN(number)) {
            throw new Error('请输入数字或者数字字符串~');
        }
        return this - number;
    };
    console.log((5).add(3).minus(2));
    /* 
    	安全解法
    	考虑到js的数字是双精度的,所以要考虑js的最大安全整数位数,和js的小数出现的问题。
    */
    
    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
      }
    }