Home > Blockchain >  Calc (add, sub, result)
Calc (add, sub, result)

Time:12-03

I need your help, my friends.

There is a task:

Implement Calc class with sub / add / result methods.

In the constructor, we can pass the initial immutable value (by default 0), then add and subtract from it using the add and sub methods. The add / sub call can be chained (fluent interface), the methods return a new class object. By calling result (), we get the result of the calculations.

For example:

const calc = new Calc();
calc.result(); // 0
calc.add(5).result(); // 0   5 = 5
calc.add(3).sub(10).result(); // 0   3 - 10 = -7

const ten = calc.add(10);
ten.sub(5).result(); // 10 - 5 = 5
ten.result(); // 10

This is a class

class Calc {
   
}

My try:

class Calc {
    constructor (num = 0) {
        this.num = num;
    }

    add (a) {
        this.num  = a
        return this
    }

    sub (a) {
        this.num -= a
        return this
    }

    result () {
        return this.num
    }
}

The test shows it:

FAIL test.js
  calc
    ✓ must return an instance of the Calc class in sub methods (5ms)
    ✓ must implement fluent interface (1ms)
    ✓ must correctly implement mathematical operations (5ms)
    ✕ must ensure the immutability of class instances (2ms)
    ✕ must ensure the immutability of class 2 instances (2ms)

Help me to complete the task correctly, please

CodePudding user response:

My guess is that you need to return a new Calculator instance every time you do an operation:

class Calc {
  constructor(num = 0) {
      this.num = num;
  }

  add(a) {
      return new Calc(this.num a);
  }

  sub(a) {
      return new Calc(this.num-a);
  }

  result() {
      return this.num;
  }
}
  • Related