-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscript.js
More file actions
75 lines (63 loc) · 2.07 KB
/
script.js
File metadata and controls
75 lines (63 loc) · 2.07 KB
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
const CALC_DISPLAY = document.querySelector('h1');
const INPUT_BTNS = document.querySelectorAll('button');
const CLEAR_BTN = document.getElementById('clearBtn');
let firstVal = 0;
let opVal = '';
let awaitNextVal = false;
const calculationObj = {
'/': (firstNum, secondNum) => firstNum / secondNum,
'*': (firstNum, secondNum) => firstNum * secondNum,
'+': (firstNum, secondNum) => firstNum + secondNum,
'-': (firstNum, secondNum) => firstNum - secondNum,
'=': (firstNum, secondNum) => secondNum,
}
function sendNumberValue(num){
if(awaitNextVal){
CALC_DISPLAY.textContent = num;
awaitNextVal = false;
} else{
const displayValue = CALC_DISPLAY.textContent;
CALC_DISPLAY.textContent = displayValue === '0' ? num : displayValue + num;
}
}
function resetValues() {
let firstVal = 0;
let opVal = '';
let awaitNextVal = false;
CALC_DISPLAY.textContent = '0';
}
function addDecimal(){
if(awaitNextVal){
return;
}
if(!CALC_DISPLAY.textContent.includes('.')){
CALC_DISPLAY.textContent = `${CALC_DISPLAY.textContent}.`;
}
}
function useOperator(op){
const currentVal = Number(CALC_DISPLAY.textContent);
if(opVal && awaitNextVal){
opVal = op;
return;
}
if(!firstVal){
firstVal = currentVal;
} else {
const calc = calculationObj[opVal](firstVal, currentVal);
CALC_DISPLAY.textContent = +parseFloat((calc).toFixed(5));
firstVal = calc;
}
awaitNextVal = true;
opVal = op;
}
//Event L for num, op and decimal
INPUT_BTNS.forEach(input => {
if(input.classList.length === 0){
input.addEventListener('click', () => sendNumberValue(input.value));
} else if (input.classList.contains('operator')){
input.addEventListener('click', () => useOperator(input.value));
} else if (input.classList.contains('decimal')){
input.addEventListener('click', () => addDecimal());
}
})
CLEAR_BTN.addEventListener('click', resetValues);