I could really use your assistance, friends.
Here's the challenge:
Create a Calc class with methods for subtraction, addition, and obtaining the result.
The constructor should allow us to input an initial immutable value (default is 0), which can then be modified using the add and sub methods.
Both add and sub methods should be chainable, returning a new class object each time they are called.
Calling result()
will give us the final result of the calculations.
For instance:
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
You'll find the class structure below:
class Calc {
}
This is how I've attempted it so far:
class Calc {
constructor (value = 0) {
this.value = value;
}
add (num) {
this.value += num;
return this;
}
sub (num) {
this.value -= num;
return this;
}
result () {
return this.value;
}
}
Here's the test results:
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)
I'd appreciate your help in completing this task accurately. Thank you!