How can i chain multiple operations in my calculator using JS?

Viewed 378
function add(a, b) { return content.textContent = parseFloat(a) + parseFloat(b); }
function sub(a, b) { return content.textContent = parseFloat(a) - parseFloat(b); }
function mul(a, b) { return content.textContent = parseFloat(a) * parseFloat(b); }
function div(a, b) { return content.textContent = parseFloat(a) / parseFloat(b); }
function operate(opertor, a, b) {
    if (opertor == '+') {
        add(a, b)
    }
    if (opertor == '-') {
        sub(a, b)
    }
    if (opertor == '*') {
        mul(a, b)
    }
    if (opertor == '÷') {
        div(a, b);
    }
}


let content = document.getElementById('content'); // getting the display
let button = document.querySelectorAll('.number'); // selecting all buttons with numeric values


// for each button, when pressed populate the display.
button.forEach(function (buttons) {
    buttons.addEventListener('click', function () {
        content.textContent += buttons.textContent;

    })
})

Working When the User presses an operator, the value in the display is saved in previousOperand, the display flushed and the operators value is saved in sign. Next a click event for the equal button. When the user clicks on equal, the textContent of display is saved in currentOperand and then operate() function is called by the equal button with parameters sign,previousOperand,currentOperand and the operate() function checks the sign and calls an appropriate function. How can i make my calculator to chain operations for example if the user inputs 3 then presses * and then inputs 2 and then again presses * and inputs 4. I want the calculator to first evaluate 3*2 and then with the obtained result multiply it with 4.

1 Answers

You need to implement an order of operations stack. You need to unwind the math the same way you do any other equation.

PEMDAS

This stack of math can get pretty fun so good luck. I'm not sure why you want to write this anyways since the engine literally has this exact thing already built, and completely working.

Related