Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to concatenate function with javascript closure and object

i’m trying to find a solution to this exercise:

Implement the calculate function that adds an object that gives the ability to do the four
mathematical operations (addition, subtraction, multiplication and division) on the same number and finally print out the result.

function calculate() {

}

const calculator = calculate();
calculator.add(2).add(4).multiply(3).sub(1).sub(3).divide(2).printResult(); // result will be: 7
console.log(calculator)

so, what is the right way to solve this (and if you can add comment will be appreciated

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can return the object itselft.

function calculate() {
  return {
    result: 0,
    add: function(num) {
      this.result += num;
      return this;
    },
    sub: function(num) {
      this.result -= num;
      return this;
    },
    multiply: function (num) {
      this.result = this.result * num;
      return this;
    },
    divide: function (num) {
      this.result /= num;
      return this;
    },
    printResult: function () {
      return this.result;
    }
 }
};

const calculator = calculate();
const result = calculator.add(2).add(4).multiply(3).sub(1).sub(3).divide(2).printResult(); // result will be: 7
console.log(result);

Make sure to understand how this works in JavaScript. For instance, using functions is different than using arrow functions.

Reference: JavaScript this

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading