-
Notifications
You must be signed in to change notification settings - Fork 0
/
calc.js
90 lines (87 loc) · 2.06 KB
/
calc.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
let ans = document.querySelector("#ans");
let fNum, sNum, op, op2, equal;
// when user enter number
let EnterNumber = function (e) {
// if second number after enter the operator
if (op) {
ans.value = "";
ans.value += e;
/* make another operator variable to allow the user to...
...enter more than one number in second number*/
op2 = op;
op = "";
equal = false;
// if first number
} else {
ans.value += e;
equal = false;
}
};
// when user enter operater
let EnterOperator = function (o) {
// if there operator entered and user enter another one
if (op || op2) {
EnterEqual();
fNum = Number(ans.value);
op = o;
// if there no operater entered yet
} else {
fNum = Number(ans.value);
op = o;
}
};
// when user enter equal
let EnterEqual = function () {
// merge two operator variables to op
op ? (op = op) : (op = op2);
// if equal pressed when no new numbers added
if (equal) {
sNum = Number(ans.value);
// if equal pressed when new numbers added
} else {
sNum = Number(ans.value);
// check the operater cases
switch (op) {
case "+":
ans.value = fNum + sNum;
break;
case "*":
ans.value = fNum * sNum;
break;
case "-":
ans.value = fNum - sNum;
break;
case "/":
// check if user make zero division
if (sNum) {
ans.value = fNum / sNum;
} else {
// if zero division return 0
ans.value = 0;
}
break;
}
}
equal = true;
op = op2 = "";
};
// when user enter clear
let EnterClear = function () {
ans.value = fNum = sNum = op = op2 = "";
};
//---------------------------//
//---------with eval()-------//
//---------------------------//
// let ans = document.querySelector("#ans");
// let EnterNumber = function (e) {
// ans.value += e;
// };
// let EnterOperator = function (e) {
// ans.value += e;
// };
// let EnterEqual = function () {
// ans.value = eval(ans.value);
// };
// let EnterClear = function () {
// ans.value = "";
// };