-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
98 lines (85 loc) · 2.42 KB
/
script.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
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
let operator = '';
let firstOperand = '';
let secondOperand = '';
let displayValue = '';
let result = '';
// DOM nodes
const calculator = document.querySelector('.calculator');
const display = calculator.querySelector('.display');
const keypad = calculator.querySelector('.keypad');
const keys = keypad.querySelectorAll('.keys-btns');
const plusBtn = keypad.querySelector('#plus');
const minusBtn = keypad.querySelector('#minus');
const multiplyBtn = keypad.querySelector('#multiply');
const divideBtn = keypad.querySelector('#divide');
const equalBtn = keypad.querySelector('#equal');
const clear = keypad.querySelector('#clear');
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
function multiply(a, b) {
return a * b;
}
function divide(a, b) {
if (b === 0) {
return alert(`You cant't divide by 0`);
} else return a / b;
}
function operate(operatorChoose, numOne, numTwo) {
return operatorChoose(numOne, numTwo);
}
function populateValueOnDisplay() {
keys.forEach(item => {
item.addEventListener('click', e => {
if (display.textContent.length < 13 && e.target.value) {
let populate = display.textContent.startsWith('0')
? (display.textContent = e.target.value)
: (display.textContent += e.target.value);
displayValue = +populate;
console.log(displayValue);
}
});
});
}
populateValueOnDisplay();
plusBtn.addEventListener('click', () => {
firstOperand = displayValue;
display.textContent = 0;
operator = add;
});
minusBtn.addEventListener('click', () => {
firstOperand = displayValue;
display.textContent = 0;
operator = subtract;
});
multiplyBtn.addEventListener('click', () => {
firstOperand = displayValue;
display.textContent = 0;
operator = multiply;
});
divideBtn.addEventListener('click', () => {
firstOperand = displayValue;
display.textContent = 0;
operator = divide;
});
clear.addEventListener('click', () => {
displayValue = 0;
display.textContent = 0;
operator = '';
firstOperand = '';
secondOperand = '';
});
equalBtn.addEventListener('click', () => {
if (firstOperand || secondOperand) {
secondOperand = displayValue;
displayValue = +operate(operator, firstOperand, secondOperand);
console.log('it res', displayValue);
display.textContent = displayValue;
if (display.textContent.length > 14) {
display.textContent = 'NaN';
}
} else return console.log('error');
});