Would you like to clone this notebook?

When you clone a notebook you are able to make changes without affecting the original notebook.

Cancel

Implement a chain calculator

node v18.11.0
version: 1.0.0
endpointsharetweet
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