/
index.js
147 lines (130 loc) · 3.07 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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
const nums = [7, 8, 9, 4, 5, 6, 1, 2, 3, 0];
const ops = ["/", "*", "-", "+"];
const ids = {
7: "seven",
8: "eight",
9: "nine",
4: "four",
5: "five",
6: "six",
1: "one",
2: "two",
3: "three",
0: "zero",
"/": "divide",
"*": "multiply",
"-": "subtract",
"+": "add",
};
class App extends React.Component {
state = {
lastPressed: undefined,
calc: "0",
operation: undefined,
};
handleClick = (e) => {
const { calc, lastPressed } = this.state;
const { innerText } = e.target;
switch (innerText) {
case "AC": {
this.setState({
calc: "0",
});
break;
}
case "=": {
const evaluated = eval(calc);
this.setState({
calc: evaluated,
});
break;
}
case ".": {
const splitted = calc.split(/[\+\-\*\/]/);
const last = splitted.slice(-1)[0];
if (!last.includes(".")) {
this.setState({
calc: calc + ".",
});
}
break;
}
default: {
let e = undefined;
// check for other op
if (ops.includes(innerText)) {
if (ops.includes(lastPressed) && innerText !== "-") {
// oh boii...
const lastNumberIdx = calc
.split("")
.reverse()
.findIndex((char) => char !== " " && nums.includes(+char));
e = calc.slice(0, calc.length - lastNumberIdx) + ` ${innerText} `;
} else {
e = `${calc} ${innerText} `;
}
} else {
e = calc === "0" ? innerText : calc + innerText;
}
this.setState({
calc: e,
});
}
}
this.setState({
lastPressed: innerText,
});
};
render() {
const { currentNumber, calc } = this.state;
return (
<div className="calculator">
<div id="display" className="display">
{calc}
</div>
<div className="nums-container">
<button
className="big-h light-grey ac"
onClick={this.handleClick}
id="clear"
>
AC
</button>
{nums.map((num) => (
<button
className={`dark-grey ${num === 0 && "big-h"}`}
key={num}
onClick={this.handleClick}
id={ids[num]}
>
{num}
</button>
))}
<button
className="light-grey"
onClick={this.handleClick}
id="decimal"
>
.
</button>
</div>
<div className="ops-container">
{ops.map((op) => (
<button
className="orange"
key={op}
onClick={this.handleClick}
id={ids[op]}
>
{op}
</button>
))}
<button className="orange" onClick={this.handleClick} id="equals">
=
</button>
</div>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("app"));