-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
101 lines (84 loc) · 2.29 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
99
100
101
//*Functions by specific operations - they get called by the main function
function add(firstNum, secondNum) {
return Number(firstNum) + Number(secondNum);
}
function subtract(firstNum, secondNum) {
return firstNum - secondNum;
}
function multiply(firstNum, secondNum) {
return firstNum * secondNum;
}
function divide(firstNum, secondNum) {
return firstNum / secondNum;
}
function modulus(firstNum, secondNum) {
return firstNum % secondNum;
}
//*Variables for input - they go into the operate function
let firstNum;
let secondNum;
let operator;
//*Init the display
const display = document.querySelector('.display');
let displayValue = '';
//*Main function that calls functions for specific operations
function operate(firstNum, secondNum, operator) {
switch (operator) {
case '+':
return add(firstNum, secondNum);
case '-':
return subtract(firstNum, secondNum);
case '*':
return multiply(firstNum, secondNum);
case '/':
return divide(firstNum, secondNum);
case '%':
return modulus(firstNum, secondNum);
}
}
//*NUMBERS
const numbers = document.querySelectorAll('.numbers');
numbers.forEach((number) => {
number.addEventListener('click', () => {
displayValue = displayValue + String(number.textContent);
display.textContent = displayValue;
});
});
//*OPERATIONS
const operations = document.querySelectorAll('.operations');
operations.forEach((operation) => {
operation.addEventListener('click', () => {
if (firstNum === undefined) {
firstNum = displayValue;
}
operator = operation.textContent;
display.textContent = operation.textContent;
displayValue = '';
});
});
//*EQUALS
const equals = document.querySelector('#equals');
equals.addEventListener('click', () => {
secondNum = displayValue;
// Check if secondNum is a valid number
if (parseFloat(secondNum) === 0 && operator === '/') {
window.location.href =
'https://i.kym-cdn.com/photos/images/original/001/734/672/7a0.jpg';
} else if (!isNaN(parseFloat(secondNum))) {
display.textContent = operate(
parseFloat(firstNum),
parseFloat(secondNum),
operator
).toFixed(3);
firstNum = display.textContent;
secondNum = '';
}
});
//*CLEAR
const ac = document.querySelector('#ac');
ac.addEventListener('click', () => {
display.textContent = '';
displayValue = '';
firstNum = undefined;
operator = '';
});