2

am trying to create a calculator in react but when i do the calulaculations it gives me that syntax Error. For example when calaculate different numbers day (30 + 23423 - 3428 *5235) it gives me that error. also i cant get my Reset and backspace and decimal to work. Can someone please help

here is my code

import React, { Component } from 'react'
import Button from "./components/Button";
import Input from "./components/Input";
import {buttonData} from "./components/Data"


class App extends Component {
    constructor(props) {
        super(props)
        this.state = {
            input: [],
            result: 0,
            operator: "+"
        }
    }
    calculate = (num1, operator, num2) => {
        let result;
        // console.log("math");
        if(!isNaN(num2)) {
        result = eval(num1 + operator + num2) 
        this.setState({result})
        }
    }

    handleClick = (button) => {
    let input = [...this.state.input]
    let result = this.state.result;
    let operator = this.state.operator;
    const num = parseFloat(input.join(''))

    switch(true) {
        case /[+-\/\*]/.test(button):
        // console.log(operator);
        this.calculate(result, operator, num)
        operator = button;
        input = operator;
        break

        case/\d/.test(button):
        // console.log(button);
        if(/[+-\/\*]/.test(button)){
            input = []
            }
            input.push(button)
        break
    }
    
    if(button === "="){
        this.calculate(result, operator, num)
    }
    else if(button === "C"){
        this.reset()
    }
    else if(button === "CE"){
        this.backspace()
    }
    else if(button === "."){
        this.handleDecimal()
    }
    this.setState({input, operator})
};


    
    reset = () => {
        this.setState({ 
            input: "0",
            reset: []
        })
    };
    
    backspace = () => {
    this.setState({
        input: this.state.input.slice(0, -1)
    })
    };
    
    handleDecimal = () => {
    const { input } = this.state;
    // ! add the point only if no point is already included
    if(!/\./.test(input)) {
        this.setState({input: `${input}.`})
    }
    }
    
    
    
    render() {
        return (
        <div className="app">
        <div className="calc-wrapper">
            <h2>Tony's Calculator</h2>
            <div id="display" >
            <Input input={this.state.input}
            result={this.state.result}
            />
            </div>
            {buttonData.map((item) => {
                let name = item.button;
                let id = item.id;
            return <Button 
            key={id} 
            name={name} 
            id={id}
            value={name} 
            handleClick={this.handleClick} 
            />
            } )
            } 
        </div>
    </div>
        )
    }
}

export default App;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

enter link description here

  • 1
    Where do you get this error? Please post a [mcve] showcasing the relevant code as it's hard to debug the entire application – VLAZ Nov 25 '20 at 10:19
  • The error is in the calculate function – Lugangastar Nov 25 '20 at 10:22
  • What is the input that goes in this function and causes the issue? – VLAZ Nov 25 '20 at 10:22
  • I'm not sure how to answer that but have linked github may you can run the code and see what am talking about – Lugangastar Nov 25 '20 at 10:25
  • 1
    I'm unable to run this code right now. And the answer is simple - *you* are able to run it, so debug the application and at the point where you get the error, check what `num1`, `operator`, and `num2` are. I suspect it's something like `num1="1 +"`, `operator="+"`, `num2="2"`. But I might be wrong. It's hard for me to track down what would happen using the code alone. – VLAZ Nov 25 '20 at 10:31
  • As a general rule, people are happy to help if the code is all included in the question, but very few people will be willing to clone and build your repo just to debug something for you. Have a look at the link in VLAZ's first comment for some background on the ideal way to do this. – DBS Nov 25 '20 at 10:35
  • @DBS [further resource for self-help](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) – VLAZ Nov 25 '20 at 10:36
  • BTW, "enter link description here" is actually a horrible link description. You are meant to replace that text with a description of where that link goes to. – Heretic Monkey Mar 01 '22 at 16:15

1 Answers1

1

The error happens when you try to use eval() or alert() with a mathematical expression that contains -- or ++

Ex:

alert(-50--30.25*32)

will throw: Uncaught SyntaxError: invalid increment/decrement operand

So, you need to surround your value by parenthesis or replace your signs with a single sign.

Ex:

alert(-50-(-30.25)*32)

Or:

str.replace(/[-]{2}|[+]{2}/g, '+')

I would use parenthesis if I was constructing a string and regex if I was reading a string.