Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

254
Views
Calc (add, sub, result)

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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;
  }
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!