-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
106 lines (89 loc) · 2.56 KB
/
index.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
102
103
104
105
106
const calculator = {
displayNumber: '0',
firstNumber: null,
secondNumberTurn: false,
operator: null,
};
function typeNumber(number) {
const { displayNumber, secondNumberTurn } = calculator;
if (secondNumberTurn === true) {
calculator.displayNumber = number;
calculator.secondNumberTurn = false;
} else {
calculator.displayNumber = displayNumber === '0' ? number : displayNumber + number;
}
console.log(calculator);
}
function operatorController(newOperator) {
let { firstNumber, displayNumber, operator} = calculator;
const numberTyped = parseInt(displayNumber);
if (operator && calculator.secondNumberTurn) {
calculator.operator = newOperator;
return;
}
if (firstNumber === null && !isNaN(numberTyped)) {
calculator.firstNumber = numberTyped;
} else if (operator) {
const result = doCalculation(firstNumber, numberTyped, operator);
console.log(result);
calculator.displayNumber = String(result);
calculator.firstNumber = result;
}
calculator.secondNumberTurn = true;
calculator.operator = newOperator;
console.log(calculator);
}
function doCalculation(firstNumber, secondNumber, operator) {
if (operator === '+') {
return firstNumber + secondNumber;
} else if (operator === '-') {
return firstNumber - secondNumber;
} else if (operator === '*') {
return firstNumber * secondNumber;
} else if (operator === '/') {
return firstNumber / secondNumber;
}
return secondNumber;
}
function clearDisplay() {
calculator.displayNumber = '0';
calculator.firstNumber = null;
calculator.secondNumberTurn = false;
calculator.operator = null;
}
function fillDisplay(event) {
const display = document.querySelector('.calculator-display');
display.value = calculator.displayNumber;
};
fillDisplay();
function deleteNumber() {
const display = document.querySelector('.calculator-display');
display.value = display.value.substr(0, display.value.length - 1);
calculator.displayNumber.length > 1 ? calculator.displayNumber = display.value : calculator.displayNumber = '0';
};
const keyRows = document.querySelector('.rows');
keyRows.addEventListener('click', (event) => {
const { target } = event;
const { value } = target;
if (!target === 'button') {
return;
}
switch (value) {
case '+':
case '-':
case '*':
case '/':
case '=':
operatorController(value);
break;
case '⬅️':
deleteNumber();
break;
case 'clear':
clearDisplay();
break;
default:
typeNumber(value);
}
fillDisplay();
});