ReactCHALLENGES
💻 Challenges🎁 Referral Program🐞 Report a Bug

© 2025 reactchallenges.com

Terms of ServicePrivacy PolicyContact

#19Calculator
60min

Overview

Build a simple calculator that supports basic arithmetic operations, decimal numbers, and negative values, while handling edge cases in user input.

Requirements

  • Display the current expression as the user types.
  • Evaluate mathematical expressions correctly when the equals button is pressed.
  • Support the four basic operations: addition, subtraction, multiplication, and division.
  • Allow decimal numbers and negative numbers.
  • Prevent invalid inputs or sequences:
    • The expression cannot start with +, *, or /.
    • The expression can start with - to represent a negative number.
    • Disallow consecutive operators except when using - to indicate a negative number.
    • Avoid multiple dots within the same number.
    • Prevent evaluation when the last element is an operator or when the expression is empty.
  • Handle negative numbers properly after any operator.
  • Prevent more than two consecutive - signs.
  • Replace leading zeros when typing new numbers (e.g., 03 → 3).
  • Allow chaining of operations and continuous usage after evaluating a result:
    • If a result is displayed and the user presses an operator, continue from that result.
    • If a result is displayed and the user presses a number, start a new expression.
  • Clear the display and reset the calculator when pressing C.

Notes

  • The display should show either the full expression or the result, depending on context.
  • Expressions must update immediately as buttons are pressed.
  • Consecutive operators must be handled gracefully (e.g., replacing the previous one if needed).
  • Negative numbers after operators (e.g., 5*-2) must be valid.
  • The calculator should handle decimal precision correctly (round results to two decimals if needed).
  • Avoid any syntax errors or invalid evaluations when using eval or equivalent.
  • Clearing should reset both the expression and the result.

Tests

  1. basic sum operation
  2. more complex sum operation
  3. does not allow '+' as the first value
  4. does not allow '*' as the first value
  5. does not allow '/' as the first value
  6. allows '-' as the first value (negative numbers)
  7. allow negative numbers after any operator
  8. prevents more than two consecutive '-' and allows negative numbers correctly
  9. handle leading zeros correctly
  10. if there is a result and a number or operator is pressed
  11. prevent multiple dots in the same number
  12. prevent consecutive operators
  13. concatenate numbers/dots if the last element is a number
  14. prevent evaluating if the last element is an operator
  15. prevent evaluating if is empty
  16. clear
Subscribe to StartBack