-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCalculator.js
29 lines (28 loc) · 988 Bytes
/
Calculator.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
const display=document.querySelector(".display");
const buttons=document.querySelectorAll("button");
const specialChar=["%","*","/",".", "+","="];
let output="";
//Define function to calculate based on click button
const calculate=(btnValue)=>{
if(btnValue==="=" && btnValue!==""){
//If output has %,replce with /100 before evaluating
output=eval(output.replace("%","/100"));
}else if(btnValue==="cl"){
output=" "
}else if(btnValue==="del"){
//remove last character
output=output.toString().slice(0,-1);
} else{
//if outout is empty and button is last specialcharacter then returns
if(output==="" && specialChar.includes(btnValue)) return;
output+=btnValue;
}
display.value=output;
}
//Add event listener to buttons, call calculate on click
buttons.forEach(button=>{
//Button click listener calls calculate() with dataset value as argument
button.addEventListener("click",e=>{
calculate(e.target.dataset.value);
});
})