Advertisement
SergioG_0823849

calculator

Apr 4th, 2024
712
0
305 days
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class Calculator {
  2.   constructor() {
  3.     this.result = 0;
  4.   }
  5.  
  6.   add(num) {
  7.     this.result += num;
  8.     return this;
  9.   }
  10.  
  11.   subtract(num) {
  12.     this.result -= num;
  13.     return this;
  14.   }
  15.  
  16.   multiply(num) {
  17.     this.result *= num;
  18.     return this;
  19.   }
  20.  
  21.   divide(num) {
  22.     if (num === 0) {
  23.       throw new Error("Cannot divide by zero");
  24.     }
  25.     this.result /= num;
  26.     return this;
  27.   }
  28.  
  29.   getResult() {
  30.     return this.result;
  31.   }
  32. }
  33.  
  34. // Test method chaining
  35. const calc = new Calculator();
  36. const result = calc.add(5).multiply(2).subtract(3).divide(2).getResult();
  37. console.log(result); // Output: 4
  38.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement