Simple JavaScript Calculator with Method Chaining
Intuition\nThe idea behind this code is to create a calculator that can do basic math like addition, subtraction, multiplication, division, and raising a number
# Intuition\nThe idea behind this code is to create a calculator that can do basic math like addition, subtraction, multiplication, division, and raising a number to a power. It\'s like a regular calculator but in code form.\n\n# Approach\nThe Calculator class is implemented with methods for each mathematical operation (add, subtract, multiply, divide, and power). These methods modify the result property of the Calculator instance accordingly and return this to enable method chaining. The constructor initializes the result property with the initial value provided.\n\nWhen performing division, the method checks if the divisor is zero, and if so, it throws an error message.\n\n# Complexity\n- Time complexity:\nEach operation in the Calculator class takes constant time complexity, as they involve simple arithmetic operations.\nMethod chaining allows multiple operations to be performed in a single expression, but the time complexity remains constant for each operation.\nTherefore, the time complexity for each operation and method chaining is O(1).\n\n- Space complexity:\nThe space complexity is also O(1) as the space used does not depend on the input size but rather on the number of variables and objects created, which is constant in this case.\n\n# Code\n```\nclass Calculator {\n    \n    /** \n     * @param {number} value\n     */\n    constructor(value) {\n        this.result = value;\n    }\n    \n    /** \n     * @param {number} value\n     * @return {Calculator}\n     */\n    add(value){\n        this.result += value;\n        return this;\n    }\n    \n    /** \n     * @param {number} value\n     * @return {Calculator}\n     */\n    subtract(value){\n        this.result -= value;\n        return this;\n    }\n    \n    /** \n     * @param {number} value\n     * @return {Calculator}\n     */  \n    multiply(value) {\n        this.result *= 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.result /= value;\n        return this;\n    }\n    \n    /** \n     * @param {number} value\n     * @return {Calculator}\n     */\n    power(value) {\n        this.result **= value;\n        return this;\n    }\n    \n    /** \n     * @return {number}\n     */\n    getResult() {\n        return this.result;\n    }\n}\n```
['JavaScript']