Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Calculator {
- constructor() {
- this.result = 0;
- }
- add(num) {
- this.result += num;
- return this;
- }
- subtract(num) {
- this.result -= num;
- return this;
- }
- multiply(num) {
- this.result *= num;
- return this;
- }
- divide(num) {
- if (num === 0) {
- throw new Error("Cannot divide by zero");
- }
- this.result /= num;
- return this;
- }
- getResult() {
- return this.result;
- }
- }
- // Test method chaining
- const calc = new Calculator();
- const result = calc.add(5).multiply(2).subtract(3).divide(2).getResult();
- console.log(result); // Output: 4
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement