Implementing a Calculator with Method Chaining in JavaScript
Intuition\nWhen asked to design a calculator class that allows consecutive operations using method chaining, my first thoughts revolved around ensuring that eac
## Intuition\nWhen asked to design a calculator class that allows consecutive operations using method chaining, my first thoughts revolved around ensuring that each method modifies the internal state (`result` or `value`) and returns the instance of the class (`this`). This enables the next operation to continue working on the updated state, making chaining possible. Additionally, handling division by zero properly is crucial.\n\n## Approach\nTo implement the calculator class, I followed these steps:\n\n1. **Define the Constructor**: The constructor accepts an initial value and stores it in a class property (`this.value`). This will serve as the starting point for all operations.\n\n2. **Method Chaining**: Each mathematical operation (addition, subtraction, multiplication, division, and power) modifies the internal state (`this.value`) and returns `this`, which refers to the current instance of the class. This allows consecutive operations to be performed in a single line of code.\n\n3. **Error Handling**: For the division operation, I included a condition to check if the divisor is `0`. If so, an error is thrown to prevent division by zero.\n\n4. **Get Result**: The `getResult()` method simply returns the current value stored in the class.\n\nBy following this approach, the calculator class allows users to perform a sequence of mathematical operations in a concise and readable manner.\n\n### Detailed Explanation of `this` Keyword\nIn JavaScript, the `this` keyword refers to the object that is executing the current function. In the context of a class, `this` refers to the instance of the class. Here\u2019s how `this` is used in the `Calculator` class:\n\n1. **Constructor (`this.value`)**: \n   - The constructor initializes the internal state by assigning the passed value to `this.value`. Here, `this` refers to the instance of the `Calculator` class being created.\n\n2. **Method Chaining**: \n   - In each method (`add`, `subtract`, `multiply`, `divide`, `power`), `this.value` is updated based on the operation. After updating, `return this;` is used. This ensures that the current instance is returned, allowing further method calls on the same instance.\n\nFor example:\n```javascript\nlet calc = new Calculator(10);\ncalc.add(5).subtract(3).multiply(2);\n```\n- When `calc.add(5)` is called, `this.value` is updated to `15` and `this` (the `Calculator` instance) is returned. \n- Now, `.subtract(3)` is called on the returned instance, updating `this.value` to `12` and returning the same instance.\n- Finally, `.multiply(2)` operates on the instance where `this.value` is `12`, resulting in `24`.\n\nBy using `this`, each method ensures it operates on the current instance\'s state and returns the instance itself, enabling a chain of operations.\n\n### Dry Run\n\nLet\'s walk through an example step by step:\n\n```javascript\nlet calc = new Calculator(10);\nlet result = calc.add(5).subtract(3).multiply(2).getResult();\n```\n\n- **Step 1 (Initialization)**: \n   - `new Calculator(10)` creates an instance with `this.value = 10`.\n   \n- **Step 2 (Addition)**: \n   - `calc.add(5)` updates `this.value` to `15` (`10 + 5`). It then returns the `calc` instance.\n\n- **Step 3 (Subtraction)**: \n   - `.subtract(3)` updates `this.value` to `12` (`15 - 3`). It returns the `calc` instance.\n\n- **Step 4 (Multiplication)**: \n   - `.multiply(2)` updates `this.value` to `24` (`12 * 2`). It returns the `calc` instance.\n\n- **Step 5 (Get Result)**: \n   - `.getResult()` returns `this.value`, which is `24`.\n\nFinal Output:\n- `result` is `24`.\n\n### Complexity\n\n- **Time Complexity**: Each operation (addition, subtraction, multiplication, division, power) performs a constant-time operation. Therefore, the time complexity for each method is $$O(1)$$.\n\n- **Space Complexity**: The space complexity is also $$O(1)$$ since no additional data structures are used, and operations are performed in place.\n\n## Code\n```javascript\nclass Calculator {\n    \n    /** \n     * @param {number} value\n     */\n    constructor(value) {\n        this.value = value;\n    }\n    \n    /** \n     * @param {number} value\n     * @return {Calculator}\n     */\n    add(value) {\n        this.value += value;\n        return this;\n    }\n    \n    /** \n     * @param {number} value\n     * @return {Calculator}\n     */\n    subtract(value) {\n        this.value -= value;\n        return this;\n    }\n    \n    /** \n     * @param {number} value\n     * @return {Calculator}\n     */  \n    multiply(value) {\n        this.value *= value;\n        return this;\n    }\n    \n    /** \n     * @param {number} value\n     * @return {Calculator}\n     */\n    divide(value) {\n        if (value === 0) {\n            throw new Error(\'Division by zero is not allowed\');\n        }\n        this.value /= value;\n        return this;\n    }\n    \n    /** \n     * @param {number} value\n     * @return {Calculator}\n     */\n    power(value) {\n        this.value = Math.pow(this.value, value);\n        return this;\n    }\n    \n    /** \n     * @return {number}\n     */\n    getResult() {\n        return this.value;\n    }\n}\n```\n![image.png](https://assets.leetcode.com/users/images/1baa787d-6707-4d4b-8531-4f3f3b053a93_1724414505.2437885.png)\n
['JavaScript']