
'use strict';

const Service = require('egg').Service;

class ArithmeticService extends Service {

    /** 
     * @param num1被加数
     * @param num2加数
     */    add(num1, num2) {
        let baseNum, baseNum1, baseNum2;
        try {
            baseNum1 = num1.toString().split(".")[1].length;
        } catch (e) {
            baseNum1 = 0;
        }
        try {
            baseNum2 = num2.toString().split(".")[1].length;
        } catch (e) {
            baseNum2 = 0;
        }
        baseNum = Math.pow(10, Math.max(baseNum1, baseNum2));
        return (num1 * baseNum + num2 * baseNum) / baseNum;
    };

    /** 
     * @param num1被减数 
     * @param num2减数
     */
    sub(num1, num2) {
        let baseNum, baseNum1, baseNum2;
        try {
            baseNum1 = num1.toString().split(".")[1].length;
        } catch (e) {
            baseNum1 = 0;
        }
        try {
            baseNum2 = num2.toString().split(".")[1].length;
        } catch (e) {
            baseNum2 = 0;
        }
        baseNum = Math.pow(10, Math.max(baseNum1, baseNum2));
        let n = baseNum1 >= baseNum2 ? baseNum1 : baseNum2;
        return Number(((num1 * baseNum - num2 * baseNum) / baseNum).toFixed(n));
    };

    /** 
     * @param num1被乘数
     * @param num2乘数
     */
    mul(num1, num2) {
        let baseNum = 0;
        try {
            baseNum += num1.toString().split(".")[1].length;
        } catch (e) { }
        try {
            baseNum += num2.toString().split(".")[1].length;
        } catch (e) { }
        return Number(num1.toString().replace(".", "")) * Number(num2.toString().replace(".", "")) / Math.pow(10, baseNum);
    };

    /** 
     * @param num1被除数
     * @param num2除数
     */
    div(num1, num2) {
        let baseNum1 = 0, baseNum2 = 0;
        let baseNum3, baseNum4;
        try {
            baseNum1 = num1.toString().split(".")[1].length;
        } catch (e) {
            baseNum1 = 0;
        }
        try {
            baseNum2 = num2.toString().split(".")[1].length;
        } catch (e) {
            baseNum2 = 0;
        }
        baseNum3 = Number(num1.toString().replace(".", ""));
        baseNum4 = Number(num2.toString().replace(".", ""));
        return this.mul((baseNum3 / baseNum4), Math.pow(10, baseNum2 - baseNum1));
    }


}

module.exports = ArithmeticService;
