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 function chain in Javascript without storing previous value

I wanted a way to chain my functions together with this desired result.
The calculator always starts at 0 and calling Calculator initiates the result = 0. The calculator has a few functions that operate on this value and can be chained together. At the end of the chain, I call log which logs the result.

In this example, I call Calculator twice and my desired result is A = 100, B = 4. Instead, I get A = 100, B = 204. I understand since it’s the same object, the result doesn’t get reinitialised to 0 the 2nd time I use it.

const Calculator = {
  result: 0,
  addNumber(a) {
    this.result = this.result + a;
    return this;
  },

  multiplyNumber(a) {
    this.result = this.result * a;
    return this;
  },

  log() {
    console.log(this.result);
  }
};

// A logs 100
Calculator.addNumber(10).multiplyNumber(10).log();

// B logs 204 instead of 4
Calculator.addNumber(2).multiplyNumber(2).log();

Is there anyway I can restructure this so the 2nd time I call Calculator, it reinitialises to 0 without using a class and defining new Calculator?

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 :

Calculator is an object. It seems you’re trying to use as if it’s creating a new object each time you write Calculator.

Probably you want to do something like this:

const calculator = () => {
    return {
        result: 0,
        addNumber(a) {
            this.result = this.result + a;
            return this;
        },

        multiplyNumber(a) {
            this.result = this.result * a;
            return this;
        },

        log() {
             console.log(this.result);
        }
    };
}

// logs 100
calculator().addNumber(10).multiplyNumber(10).log();

// logs 4
calculator().addNumber(2).multiplyNumber(2).log();

Or like this:

class Calculator
{
  constructor() {
      this.result = 0;
  }
  
  addNumber(a) {
      this.result = this.result + a;
      return this;
  }

  multiplyNumber(a) {
    this.result = this.result * a;
    return this;
  }

  log() {
    console.log(this.result);
  }
}

// logs 100
(new Calculator()).addNumber(10).multiplyNumber(10).log();

// logs 4
(new Calculator()).addNumber(2).multiplyNumber(2).log();
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