Clone and edit this document
Runkit
Runkit
home page
user forum
new notebook
clone notebook
download notebook
support & documentation
log in
sign up
new notebook
help & feedback
clone this notebook
download this notebook
Sign In
Sign Up
Implement a chain calculator
node v18.11.0
version:
1.0.0
endpoint
share
tweet
This is a playground to test JavaScript. It runs a completely standard copy of Node.js on a virtual server created just for you. Every one of npm’s 300,000+ packages are pre-installed, so try it out:
class ChainCalculator { constructor(initialValue = 0) { this.value = initialValue; } add(number) { this.value += number; return this; // Return `this` to enable chaining } subtract(number) { this.value -= number; return this; } multiply(number) { this.value *= number; return this; } divide(number) { if (number === 0) { throw new Error("Division by zero is not allowed."); } this.value /= number; return this; } getResult() { return this.value; } reset() { this.value = 0; return this; } } // Example usage: const calculator = new ChainCalculator(10); const result = calculator .add(5) // 10 + 5 = 15 .subtract(3) // 15 - 3 = 12 .multiply(4) // 12 * 4 = 48 .divide(2) // 48 / 2 = 24 .getResult(); console.log(result); // Output: 24
Loading…
no comments
sign in
to comment