Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

260
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda