I have built an application where two or more values are computed. My question is how I would be able to compute 5+5= 10 instead of the way it is being computed right now where each 5+5+=10 where I have to press the + or -button before I press the equals button?

import React, {Component} from 'react';
import Screen from './components/Screen'
import OperandButtons from './components/OperandButtons'
import CalcMemory from './components/CalcMemory'

class Calculate extends Component {
    state = {
        operator: '',
        input: '',
        current: '',
        result: 0,
        memory: [],
        additionMarker: false,
        subtractionMarker: false,
        markingColor: 'green'
    };
    handleChange = (event) => {
        this.setState({
            input: event,
        });
    };
    addition = () => {
        this.setState({
            operator: '+',
            additionMarker: true,
            subtractionMarker: false,
            current: Number(this.state.input) + Number(this.state.current)
        });
    };
    subtraction = () => {
        this.setState({
            current: this.state.input,
            operator: '-',
            subtractionMarker: true,
            additionMarker: false,
        });
        this.setState(() => {
            if (this.state.current > 0) {
                let result = this.state.current - Number(this.state.input);
                console.log(result);
                return {
                    current: result,

                }
            }
        })

    };
    clear = () => {
        this.setState({
            input: 0,
        })
    };
    equals = () => {
        this.setState({
            result: this.state.current
        })
    };
    savedResults = [];
    addToMemory = () => {
        this.savedResults.push(this.state.input);
    };
    useMemory = () => {
        const toBeUsedInExpression = [...this.savedResults];
        let latestNum = toBeUsedInExpression.pop();
        this.setState({
            input: latestNum
        })
    };

    render() {
        return <React.Fragment>

            <Screen input={this.state.input} result={this.state.result} handleChange={this.handleChange}/>
            <OperandButtons addition={this.addition}
                            subtraction={this.subtraction}
                            clear={this.clear}
                            equals={this.equals}
                            additionMarker={this.state.additionMarker}
                            subtractionMarker={this.state.subtractionMarker}
                            markingColor={this.state.markingColor}
            />
            <CalcMemory addToMemory={this.addToMemory} useMemory={this.useMemory}/>
        </React.Fragment>
    }
}

export default Calculate;

expected 5+5=10 result 5+5=5.

1 Answers

0
chafik bel On

Since "input" and "current" are numbers why don't initialize them with "0". Try "parseInt" function instead of "Number".