I'm trying to build the classic javascript calculator that has to receive two numbers and an operation and return the result. It does not need to evaluate the precedence of the operations, it must only return the operations in order.
I decided to approach it using an array to store the values of the button clicks (numbers, operations, clear, and equal/result). But now I'm having trouble in storing and picking apart the fistNumber from the secondNumber. And the operation that must be made.
function operate(num1, num2, operator) {
return operator(num1, num2);
}
let bubblePad = document.querySelector("#pad");
let display = document.querySelector("#display")
let show = document.querySelector(".show");
let btn = document.querySelectorAll(".btn");
let equal = document.querySelector(".doubleBtn");
bubblePad.addEventListener("click", makeArray)
let args = []
let firstNumber = ""
let secondNumber = ""
let operator = ""
//functions
function makeArray(e) {
switch (true) {
case e.target.id === "":
case e.target.id === "pad":
console.log("the empty click was logged")
break;
/*
You’ll need to store the first number that is input into the calculator when a user presses an operator, and also save which operation has been chosen and then operate() on them when the user presses the “=” key.*/
case e.target.id === "*":
case e.target.id === "/":
case e.target.id === "+":
case e.target.id === "-":
case e.target.id === "%":
//IM STUCK - how do i split my array here, pick the operation to be made, and generate a new array that will use the next clicks to build the secondNumber
break;
case e.target.id === ".":
args.push(e.target.id);
//desable the dot if it was clicked before
break;
case e.target.id === "CE":
args.pop()
console.log(args)
break;
case e.target.id === "C":
args = [];
console.log(args);
show.textContent = "";
break;
case e.target.id === "=":
//operate(firstNumber,secondNumber,operator)
break;
default:
args.push(e.target.id)
console.log(args);
firstNumber = args.join("");
show.textContent = firstNumber;
}
}
<div id="calculator">
<div id="display">
<p class="show"> 789*3-2+5*7</p>
</div>
<div id="pad" class="pad">
<div>
<p class="btn" id="C">C</p>
</div>
<div>
<p class="btn" id="CE">CE</p>
</div>
<div>
<p class="btn" id="%">%</p>
</div>
<div>
<p class="btn" id="/">/</p>
</div>
<div>
<p class="btn" id="7">7</p>
</div>
<div>
<p class="btn" id="8">8</p>
</div>
<div>
<p class="btn" id="9">9</p>
</div>
<div>
<p class="btn" id="*">*</p>
</div>
<div>
<p class="btn" id="4">4</p>
</div>
<div>
<p class="btn" id="5">5</p>
</div>
<div>
<p class="btn" id="6">6</p>
</div>
<div>
<p class="btn" id="-">-</p>
</div>
<div>
<p class="btn" id="1">1</p>
</div>
<div>
<p class="btn" id="2">2</p>
</div>
<div>
<p class="btn" id="3">3</p>
</div>
<div>
<p class="btn" id="+">+</p>
</div>
<div>
<p class="btn" id=".">.</p>
</div>
<div>
<p class="btn" id="0">0</p>
</div>
<div class="doubleBtn">
<p id="=">=</p>
</div>
</div>
</div>