The Calculator is a web application that creates a calculator interface for performing basic arithmetic operations and advanced functions such as percentage and parentheses handling. It uses React and MathJS to manage the calculator's state and operations.
expression
: An array representing the current mathematical expression in the calculator. It is updated when numbers, operations, or other elements are added.error
: A string representing any errors that occur during evaluation or input handling.
getLastAddedItem()
: Returns the last item in theexpression
array.getExpression()
: Concatenates the items in theexpression
array and returns the expression as a string.addItem(item)
: Adds an item to theexpression
array.handleNumberClick(number)
: Handles click events for numbers by adding the number to theexpression
array.removeLastItem()
: Removes the last item from theexpression
array.handleOperatorClick(operation)
: Handles click events for arithmetic operators (plus, minus, product, divide) and adjusts theexpression
accordingly.handlePointClick()
: Handles click events for the decimal point by adding it to theexpression
array while ensuring it is valid in the current context.handleParenthesesClick()
: Manages click events for parentheses, adding open and close parentheses while balancing them.handlePercentageClick()
: Handles click events for the percentage symbol, adding it to theexpression
array.handleClearAll()
: Clears all items from theexpression
array and resetserror
.handleBackspace()
: Removes the last item from theexpression
array and resetserror
.handleResultClick()
: Evaluates the current expression and displays the result. It includes error handling for empty expressions, division by zero, and invalid calculations.
NumberButton
: Renders buttons for numbers based on an array of numbers, handling the click events.CalculatorButton
: Renders buttons for specific actions such as arithmetic operations, percentage, and clear functions.RenderOutput
: Displays the formatted expression or error message.
The user can interact with the calculator using buttons to input numbers and operations. Handles the input and provides feedback such as displaying results or error messages.
- The Calculator function starts with state variables for managing the expression and error state.
- Functions for handling user input and operations follow, including managing numbers, arithmetic operators, and special operations such as percentages and parentheses.
- Components for rendering buttons (
NumberButton
,CalculatorButton
) and the display (RenderOutput
) are defined to handle user interactions and display the current state of the calculator. - The return statement contains the layout and structure of the calculator, including the header, button wrapper, and individual button sections.