2726. Calculator with Method Chaining Solution
Intuition\n Describe your first thoughts on how to solve this problem. \nCreate a single property (value) inside the constructor that stores the state of the ca
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nCreate a single property (value) inside the constructor that stores the state of the calculator. Each method performs its respective operation on (value). Return (this), a reference to the calculator instance, to support method chaining. Include error handling for division by zero. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nIn the constructor, create a single property (value) that stores the current state of the calculator. Each method excluding getResult() performs its respective operation on (value), returning (this) a reference to the calculator instance. Returning (this) allows for method chaining.  Throw an error to handle division by zero. Your getResult() method should return (this.value)\n\n# Complexity\n- Time complexity: Constant O(1)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe algorithm has constant O(1) time complexity where each operation performs constant-time arithmetic operations, excluding the power() method. \n\n- Space complexity: Constant O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nEach method uses a constant amount of additional space regardless of the input size, resulting in constant O(1) space complexity. \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```
['JavaScript']