0

I'm working on a calculator small project and I'm having some issues I can't not solve.

When I execute the first operation (i.e: 9 x 3) it will work fine, pressing 9 will store that number on currentNum and then pressing an operator will store the actual number on prevNum and will show it on displayPrevResult text content along with the operator, pressing another number will replace currentNum with the new number and then pressing equal will calculate the result of currentNum and prevNum, store it on result variable and show it on displayCurrentResult textContent while displayPrevResult text content will show the last operation (9 x 3 =).

So far it works fine with the first operation but pressing another operation and adding more numbers doesn't work as I intend to, it will replace the value of currentNum but it won't replace the operation (9 x 3 =) of displayPrevResult text content, instead, the numbers keeps adding to it.

I want the operation and the displayCurrentResult text content to keep changing everytime I execute and operation, i.e:

9 x 3 will show "9 x 3 =" on the displayPrevResult text content, then displayCurrentResult will show 18, pressing "+" and a 5 will replace the content of displayCurrentResult to "18" (last result) and replace the text content of displayPrevResult to 27 and keep operating, adding +5 to the result and displaying it, and so on...

Just right like this calculator: https://michalosman.github.io/calculator/

I haven't read the code because I'm trying to improve my logic.

const displayPrevResult = document.querySelector('.prev-result');
const displayCurrentResult = document.querySelector('.current-result');
const equal = document.querySelector('.equal');
const decimal = document.querySelector('.decimal');
const clear = document.querySelector('.clear');

const numberBtn = document.querySelectorAll('.number');
const operatorBtn = document.querySelectorAll('.operator');

let prevNum = '';
let secondNum = '';
let currentNum = '';
let result = '';
let operator = '';

equal.addEventListener('click', calculate);
// decimal.addEventListener('click', addDecimal)
clear.addEventListener('click', clearCalc);

numberBtn.forEach((button) => {
    button.addEventListener('click', (e) => {
        getNumber(e.target.textContent);
    })
})

operatorBtn.forEach((button) => {
    button.addEventListener('click', (e) => {
        getOperator(e.target.textContent);
    })
})

function calculate() {

    prevNum = Number(prevNum);
    currentNum = Number(currentNum);

    if (operator === '+') {
        result = prevNum + currentNum;
        displayCurrentResult.textContent = result;
    } if (operator === '-') {
        result = prevNum - currentNum;
        displayCurrentResult.textContent = result;
    } if (operator === 'x') {
        result = prevNum * currentNum;
        displayCurrentResult.textContent = result;
    } if (operator === '÷') {
        result = prevNum / currentNum;
        displayCurrentResult.textContent = result;
    }

    currentNum = currentNum.toString();
    prevNum = prevNum.toString();
    secondNum = currentNum;
    displayPrevResult.textContent += ' ' + secondNum + ' =';
    currentNum = '';
}

function getNumber(num) {
    currentNum += num;
    displayCurrentResult.textContent = currentNum;
}

function getOperator(op) {
    if (operator === '') {
        operator = op;
        prevNum += currentNum;
        displayPrevResult.textContent = currentNum + ' ' + ' ' + operator;
        currentNum = '';

        if (currentNum == '') {
            displayPrevResult.textContent += result;
        }
    }
}

function clearCalc() {
    prevNum = '';
    secondNum = '';
    currentNum = '';
    result = '';
    operator = '';

    displayPrevResult.textContent = '';
    displayCurrentResult.textContent = '0';
}
body {
    width: 100vw;
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
}

.calcContainer {
    background: linear-gradient(276deg, #40a179, #77cea9);
    padding: 1em;
    border-radius: 5px;
    border: 1px solid #000;
}

button {
    padding: 1em;
    margin: 0.1em;
    width: 40px;
    background: #a2ffaf;
    border: 1px solid #fff;
    border-radius: 3px;
    cursor: pointer;
}

button:hover {
    background: #72e782;
}

.clr {
    background: #87e4bd;
}

.clr:hover {
    background: #53ad88;
}

.clear {
    margin: 0em 0.1em 0.5em 0.5em;
    padding: 0;
}

.output-clear-container {
    display: flex;
}

.output {
    flex-grow: 1;
    height: 40px;
    background: #c2fcca;
    border-radius: 5px;
    border: 1px solid #fff;
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    justify-content: flex-end;
    padding-right: 0.5em;
    margin-bottom: 0.5em;
}

.par {
    margin-bottom: 0.3em;
}

.prev-result {
    font-size: 14px;
    padding-bottom: 0.3em;
    color:#40a179;
}

.current-result {
    font-size: 18px;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="styles.css">
    <script src="main.js" defer></script>
    <title>Calculator</title>
</head>
<body>
    <div class="calcContainer">
        <div class="output-clear-container">
            <div class="output">
                <div class="prev-result"></div>
                <div class="current-result">0</div>
            </div>
            <button class="clear">AC</button>
        </div>
            <div class="par">
                <button class="number">7</button>
                <button class="number">8</button>
                <button class="number">9</button>
                <button class="operator clr">÷</button>
            </div>
            <div class="par">
                <button class="number">4</button>
                <button class="number">5</button>
                <button class="number">6</button>
                <button class="operator clr">x</button>
            </div>
            <div class="par">
                <button class="number">1</button>
                <button class="number">2</button>
                <button class="number">3</button>
                <button class="operator clr">-</button>
            </div>
            <div class="par">
                <button class="decimal clr">.</button>
                <button class="number">0</button>
                <button class="equal clr">=</button>
                <button class="operator clr">+</button>
            </div>
    </div>
</body>
</html>

Thank you very much

  • 1
    Did you try debugging? Where do things go wrong? – Wyck Aug 25 '22 at 17:38
  • Yeah, I'm using the console.log() to see where I'm failing, so far I have concluded that I'm maybe reassigning different results on the variables on each function, I'm not familiarized with Chrome / FF dev tools yet (using breakpoints) so I'm debugging with pen and paper but I am stucked at the moment, maybe programming logic is not for me because I got stucked often. – Quickpois0n Aug 25 '22 at 17:43
  • 1
    I think you haven't worked out the state machine for your calculator yet. Two interesting cases that are different with your code from the example. `9x3+` and `9x3=+` Your `+` key isn't doing the right thing in either of these cases. Also, both of your calculators display differently from Windows Calc for just `9=`, although the example continues to perform adequately in spite of not displaying "9 =". – Wyck Aug 25 '22 at 18:02
  • Right, I have a problem with the arbitrary use of the `+=` when I should not, it drives me crazy sometimes, otherwise you are right, I have solved my problem but I also need to set the state machine properly before setting up my calculator, thanks a lot. – Quickpois0n Aug 25 '22 at 18:23

1 Answers1

1

It's hard to say, but I think your problem is in this function. First of all your operator isn't clear every time and this condition doesn't work And second you override your displayPrev. As I understand it, you want to keep the whole history?

function getOperator(op) {
if (operator === '') {
    operator = op;
    prevNum += currentNum;
    // should use += instead = ?
    displayPrevResult.textContent = currentNum + ' ' + ' ' + operator;
    currentNum = '';
    // operator = '' clear?
    if (currentNum == '') {
        displayPrevResult.textContent += result;
    }
}

}

Upd.

Variables in the end of calculate

currentNum = currentNum.toString();
prevNum = prevNum.toString();

secondNum = currentNum;
displayPrevResult.textContent += ' ' + secondNum + ' =';

currentNum = result;
prevNum = '';
operator = '';

And getOperator function

function getOperator(op) {
if (operator === '') {
    operator = op;
    prevNum += currentNum;
    displayPrevResult.textContent = currentNum + ' ' + ' ' + operator;
    currentNum = '';
    // if (currentNum == '') {
    //     displayPrevResult.textContent += result;
    // }
}

}

Rusty Nail
  • 120
  • 1
  • 7
  • 1
    Yeah clearing the `operator` won't make much difference, I wan't to override the last `displayPrevResult` text content with new result, like: 9 + 2 = 11 (displayPrevResult shows "9 + 2 =" (the last number you press) and displayCurrentResult will show 11 which is the result), then clicking i.e "+" will replace "9 + 2 =" with "11 +", clicking 8 will now show on displayPrevResult "11 + 8 =" and displayCurrentResult 19 and so on – Quickpois0n Aug 25 '22 at 17:50
  • 1
    Are you using the result in further calculations? I didn't find. Please check update above, but I didn't handle with all history. I hope it's help a little – Rusty Nail Aug 25 '22 at 18:11
  • 1
    Thank you very much for your comment, you are correct, clearing the variables helped me a lot, I also added this: `else if (displayPrevResult.textContent !== '') { displayPrevResult.textContent += result; }` on the `getOperator` function and now seems to work as I intended. – Quickpois0n Aug 25 '22 at 18:22
  • Nice! Good luck :) – Rusty Nail Aug 25 '22 at 18:29