-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
85 lines (73 loc) · 2.11 KB
/
main.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
const reg = /[+|*|\-|/]$/;
const regToken = /(\d+\.\d+|\d+\.|\d+|\+|\-|\*|\/)$/;
var currentFormula = '';
var isLastButtonPressedEqualSign = false;
var currentValue = '';
const displayFormula = document.querySelector('#current-formula');
const displayValue = document.querySelector('#current-value');
/* CRUD */
/* CREATE */
const inputValue = (param) => {
if (currentFormula === '0') {
currentFormula = '';
}
currentFormula = currentFormula + param;
renderView(param);
}
const inputOperand = (param) => {
if (!currentFormula.match(reg)) {
currentFormula = currentFormula + param;
renderView(param);
} else {
currentFormula = currentFormula.slice(0, -1) + param;
renderView(param);
}
}
const inputDecimal = (param) => {
if (currentFormula.match(reg)) {
currentFormula = currentFormula + '0';
}
if (currentFormula.substr(-1) !== '.' && !currentValue.includes('.'))
currentFormula = currentFormula + '.';
renderView();
}
/* DELETE */
const clearAll = (param) => {
currentFormula = '0';
renderView();
}
const clearEntry = (param) => {
if (currentFormula === currentValue) {
currentFormula = '0';
} else {
currentFormula = currentFormula.slice(0, -currentValue.length);
}
renderView();
}
/* UPDATE */
const doComputation = () => {
isLastButtonPressedEqualSign = true;
renderView();
}
const changeSign = (param) => {
if(currentFormula[0] !== '-'){
currentFormula = '-' + currentFormula;
} else {
currentFormula = currentFormula.substring(1);
}
renderView();
}
/* RENDER VIEW */
const renderView = () => {
if (isLastButtonPressedEqualSign) {
currentValue = eval(currentFormula) + '';
isLastButtonPressedEqualSign = false;
displayFormula.innerHTML = currentFormula;
displayValue.innerHTML = currentValue + '';
currentFormula = currentValue;
} else {
currentValue = regToken.exec(currentFormula)[0];
displayFormula.innerHTML = currentFormula;
displayValue.innerHTML = currentValue;
}
}