Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

259
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda