Home > OS >  How to function chain in Javascript without storing previous value
How to function chain in Javascript without storing previous value

Time:08-03

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?

CodePudding user response:

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();

CodePudding user response:

Is there anyway I can restructure this so the 2nd time I call Calculator

You never call Calculator. It isn't a function. (It would be if you made it a class).


If you want to reset it to 0 then you need to do so explicitly.

You just need to decide when you want to do that.

You have two obvious choices:

  • When you call log
  • When you call a new method you add to the object which does it
  • Related