Home > Enterprise >  Operating a calculation on four basic operation using java script functions
Operating a calculation on four basic operation using java script functions

Time:11-14

I'm trying to conduct a calculating operation by summoning my pre-defined function and getting the total result instead of separate results from the same functions in case I called a function more than one time. for example :

Executed code As you can see in the picture when I called the same function twice ( calculator.sumValues(25, 4) & calculator.sumValues(45, 4)) the codes return the results separately ( sum: [ 29, 49 ] ) but i want to get the result as a sum up of both which is 29 49 = 78

Thanks for helping me out in advance.

Here's my code:

const calculator = {
    sum: [],
    subtraction: [],
    multiplication: [],
    division: [],

    sumValues: function (num1, num2) {
      this.sum.push({
        num1: num1,
        num2: num2,
      });
    },
    subtractionValues: function (num1, num2) {
      this.subtraction.push({
        num1: num1,
        num2: num2,
      });
    },
    multiplyValues: function (num1, num2) {
      this.multiplication.push({
        num1: num1,
        num2: num2,
      });
    },
    divisionValues: function (num1, num2) {
      this.division.push({
        num1: num1,
        num2: num2,
      });
    },
    resualtValues: function () {
      let result = {
        sum:[],
        sub:[],
        mul:[],
        div:[],
      };
      // **Sum Operation**
      this.sum.forEach(function (item) {
        result.sum.push(item.num1   item.num2);
      });
      // **Sub Operation**
      this.subtraction.forEach(function (item) {
        result.sub.push(item.num1 - item.num2);
      });
      // **Mul Operation**
      this.multiplication.forEach(function (item) {
        result.mul.push(item.num1 * item.num2);
      });
      // **Div Operation**
      this.division.forEach(function (item) {
        result.div.push(item.num1 / item.num2);
      });
      return result
    },
  };   

       calculator.sumValues(25, 4);
       calculator.sumValues(45, 4);
       calculator.subtractionValues(20, 5);
       calculator.multiplyValues(5, 6);
       calculator.divisionValues(45, 5);
       console.log(calculator.resualtValues());

CodePudding user response:

     this.sum.forEach(function (item) {
       result.sum.push(item.num1   item.num2);
     });

This will calculate the sum for each item in the this.sum array. It seems like what you want is to calculate the sum of all items. That is simple enough to do, you just have to keep track of the total sum outside of your loop (so you aren't just getting the sum for individual items)

      // **Sum Operation**
      totalSum = 0
      this.sum.forEach(function (item) {
        totalSum  = item.num1   item.num2
      });
      result.sum.push(totalSum)
  • Related