How to prevent a calculator operator from modifying the result when multiple operators are pressed in a row? JavaScript

Viewed 54

Creating a calculator with JavaScript, however if a user were to accidentally push an operator twice in a row, it would modify the result again based on the current values of a and b. This is primarily an issue if a user were to press the equal operator after entering an operation and then push another operator to add/subtract/etc. another number.

I am wondering if there is a way to prevent this from happening...the most logical thing I can think of would be if the operator button didn't modify the display or variables only when any two operator buttons are pressed twice in a row, though I have no idea how I would code that, and I would still need the operator to change the value of o.

Alternative solutions are welcome as well. FYI I am very new to programming so I may not understand complex solutions without a good amount of explanation.

JS code:

let clearBtn = document.getElementById('clearBtn');
let posNegBtn = document.getElementById('posNegBtn');
let divideBtn = document.getElementById('divideBtn');
let multiplyBtn = document.getElementById('multiplyBtn');
let subtractBtn = document.getElementById('subtractBtn');
let addBtn = document.getElementById('addBtn');
let equalBtn = document.getElementById('equalBtn');
let zero = document.getElementById('zero');
let decimalBtn = document.getElementById('decimalBtn');
let one = document.getElementById('one');
let two = document.getElementById('two');
let three = document.getElementById('three');
let four = document.getElementById('four');
let five = document.getElementById('five');
let six = document.getElementById('six');
let seven = document.getElementById('seven');
let eight = document.getElementById('eight');
let nine = document.getElementById('nine');
let display = document.getElementById('display');

let a = 0;
let b = 0;
let o = '-';
let currentNum;
let appendable = true;

clearBtn.addEventListener('click', clearDisplay);
posNegBtn.addEventListener('click', changePosNeg);
divideBtn.addEventListener('click', dividePressed);
multiplyBtn.addEventListener('click', multiplyPressed);
subtractBtn.addEventListener('click', subtractPressed);
addBtn.addEventListener('click', addPressed);
equalBtn.addEventListener('click', equalPressed);
zero.addEventListener('click', displayZero);
decimalBtn.addEventListener('click', displayDec);
one.addEventListener('click', display1);
two.addEventListener('click', display2);
three.addEventListener('click', display3);
four.addEventListener('click', display4);
five.addEventListener('click', display5);
six.addEventListener('click', display6);
seven.addEventListener('click', display7);
eight.addEventListener('click', display8);
nine.addEventListener('click', display9);

function clearDisplay() {
    display.value = '0';
    a = 0;
    b = 0;
    currentNum = display.value;
}

function displayZero() {
    if (appendable === true) {
        display.value += '0';
        currentNum = display.value;
    } else {
        display.value = 0;
    }
    appendable = true;
}

function displayDec() {
    if (appendable === true) {
        if (display.value.includes('.')) {
            display.value;
        } else {
            display.value += '.';
        }   
        currentNum = display.value;
    } else {
        display.value = '0.';
        appendable = true;
    }
}

function changePosNeg() {
    parseFloat(display.value *= -1);
    currentNum = display.value;
}

function display1() {
    if (display.value == '0' || appendable === false) {
        display.value ='1';
    } else {
        display.value += '1';
    } 
    currentNum = display.value;
    appendable = true;
}

function display2() {
    if (display.value == '0' || appendable === false) {
        display.value ='2';
    } else {
        display.value += '2';
    } 
    currentNum = display.value;
    appendable = true;
}

function display3() {
    if (display.value == '0' || appendable === false) {
        display.value ='3';
    } else {
        display.value += '3';
    } 
    currentNum = display.value;
    appendable = true;
}

function display4() {
    if (display.value == '0' || appendable === false) {
        display.value ='4';
    } else {
        display.value += '4';
    } 
    currentNum = display.value;
    appendable = true;
}

function display5() {
    if (display.value == '0' || appendable === false) {
        display.value ='5';
    } else {
        display.value += '5';
    } 
    currentNum = display.value;
    appendable = true;
}

function display6() {
    if (display.value == '0' || appendable === false) {
        display.value = '6';
    } else {
        display.value += '6';
    } 
    currentNum = display.value;
    appendable = true;
}

function display7() {
    if (display.value == '0' || appendable === false) {
        display.value = '7';    
    } else {
        display.value += '7';
    } 
    currentNum = display.value;
    appendable = true;
}

function display8() {
    if (display.value == '0' || appendable === false) {
        display.value = '8';
    } else {
        display.value += '8';
    } 
    currentNum = display.value;
    appendable = true;
}

function display9() {
    if (display.value == '0' || appendable === false) {
        display.value = '9';
    } else {
        display.value += '9';
    } 
    currentNum = display.value;
    appendable = true;
}

function addPressed() {
    if (a !== 0) {
        b = parseFloat(`${currentNum}`)
        operate();
    } else {
        a = parseFloat(`${currentNum}`);
    }
    o = '+';
    appendable = false;
}

function subtractPressed() {
    if (a !== 0) {
        b = parseFloat(`${currentNum}`)
        operate();
    } else {
        a = parseFloat(`${currentNum}`);
    }
    o = '-';
    appendable = false;
}

function multiplyPressed() {
    if (a !== 0) {
        b = parseFloat(`${currentNum}`)
        operate();
    } else {
        a = parseFloat(`${currentNum}`);
    }
    o = '*';
    appendable = false;
}

function dividePressed() {
    if (a !== 0) {
        b = parseFloat(`${currentNum}`)
        operate();
    } else {
        a = parseFloat(`${currentNum}`);
    }
    o = '/';
    appendable = false;
}

function equalPressed() {
    b = parseFloat(`${currentNum}`);
    operate();
}

function add() {
    display.value = a + b;
    a = parseFloat(`${display.value}`);
    appendable = false;
}

function subtract() {
    result = 
    display.value = a - b;
    a = parseFloat(`${display.value}`);
    appendable = false;
}

function multiply() {
    display.value = a * b;
    a = parseFloat(`${display.value}`);
    appendable = false;
}

function divide() {
    display.value = a / b;
    a = parseFloat(`${display.value}`);
    appendable = false;
}

function operate() {
    if (o == '-') {
        return subtract();
    } else if (o == '+') {
        return add();
    } else if (o == '*') {
        return multiply();
    } else if (o == '/') {
        return divide();
    }
}

HTML code:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Calculator</title>
        <link rel="stylesheet" href="style.css">
        <script src="script.js" defer></script>
    </head>

    <body>
        <div class="container">
            <div id="calculator">
                <input id="display" type="text" value="0">
                <div id="buttons">
                    <div id="mainBtns">
                        <div id="otherBtns">
                            <button id="clearBtn">AC</button>
                            <button id="posNegBtn">+/-</button>
                        </div>
                        <div id="numBtns">
                            <button id="seven">7</button>
                            <button id="eight">8</button>
                            <button id="nine">9</button>
                            <button id="four">4</button>
                            <button id="five">5</button>
                            <button id="six">6</button>
                            <button id="one">1</button>
                            <button id="two">2</button>
                            <button id="three">3</button>
                            <button id="zero">0</button>
                            <button id="decimalBtn">.</button>
                        </div>
                    </div>
                    <div id="operators">
                        <button id="divideBtn">/</button>
                        <button id="multiplyBtn">x</button>
                        <button id="subtractBtn">-</button>
                        <button id="addBtn">+</button>
                        <button id="equalBtn">=</button>
                    </div>
                </div>
            </div>
        </div>
    </body>
</html>

CSS code:

.container {
    display: flex;
    flex-direction: column;
}

#calculator {
    display: flex;
    flex-direction: column;
    width: 200px;
    height: 330px;
    border: 15px solid black;
    background-color: black;
    gap: 20px;
}

#display {
    background-color: gray;
    height: 60px;
    text-align: right;
    font-size: 50px;
}

#buttons {
    display: flex;
    flex-direction: row;
    gap: 10px;
    align-items: center;
}

#operators {
    display: flex;
    flex-direction: column;
    gap: 10px;
}

#divideBtn, #multiplyBtn, #subtractBtn, #addBtn, #equalBtn {
    width: 40px;
    height: 40px;
    background-color: chartreuse;
}

#mainBtns {
    display: flex;
    flex-direction: column;
    gap: 10px;
}

#numBtns {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: space-around;
    gap: 10px 10px;
}

#otherBtns {
    display: flex;
    gap: 10px;
    justify-content: space-around;
}
 
#nine, #eight, #seven, #six, #five, #four, #three, #two, #one, 
#decimalBtn, #posNegBtn {
    width: 40px;
    height: 40px;
} 

#zero, #clearBtn {
    width: 93px;
}

#clearBtn, #posNegBtn {
    background-color: aqua;
}
1 Answers

Store a variable that is a reference to the last button pressed, then in your operate function call a function that checks if the last button pressed is an operator and if it is then return early before the operation takes place.

like this:

let lastButtonPressed;

function anyOfYourOperatorFunctions() {
    if (lastButtonPressedIsOperator(lastButtonPressed))
        return null;
    else {
        ...
    }
}

function lastButtonPressedIsOperator(lastButton) {
    ...
    return true;
}

function operate() {
    if (lastButtonPressedIsOperator(lastButtonPressed))
        return null;
    if (o == '-') {
        return subtract();
    } else if (o == '+') {
        return add();
    } else if (o == '*') {
        return multiply();
    } else if (o == '/') {
        return divide();
    }
}

Related