This repository has been archived by the owner on Dec 5, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApp.js
93 lines (80 loc) · 2.14 KB
/
App.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
import React, { useState } from "react";
import { SafeAreaView, View, Text } from "react-native";
import styles from "./styles";
import Button from "./components/Button";
export default function App() {
const [inputValue, setInputValue] = useState(0);
const [previousInputValue, setPreviousInputValue] = useState(0);
const [operationSelected, setOperationSelected] = useState(null);
return (
<View style={styles.rootContainer}>
<View style={styles.displayContainer}>
<Text style={styles.displayText}>{inputValue}</Text>
</View>
<SafeAreaView style={styles.inputContainer}>
{renderButtons([
["C", "%", "/"],
[7, 8, 9, "*"],
[4, 5, 6, "-"],
[1, 2, 3, "+"],
[".", 0, "="]
])}
</SafeAreaView>
</View>
);
function renderButtons(inputButtons) {
const views = [];
for (var r = 0; r < inputButtons.length; r++) {
const row = inputButtons[r];
const inputRow = [];
for (var i = 0; i < row.length; i++) {
const input = row[i];
inputRow.push(
<Button
value={input}
key={r + "-" + i}
onPress={() => buttonPressed(input)}
/>
);
}
views.push(
<View style={styles.inputRow} key={"row-" + r}>
{inputRow}
</View>
);
}
return views;
}
function buttonPressed(input) {
switch (typeof input) {
case "number":
return handleNumberInput(input);
case "string":
return handleStringInput(input);
}
}
function handleNumberInput(num) {
setInputValue(inputValue * 10 + num);
}
function handleStringInput(string) {
if (string == "=") {
if (operationSelected) {
setInputValue(
eval(previousInputValue + operationSelected + inputValue)
);
}
return;
}
if (string == "C") {
setOperationSelected(null);
setPreviousInputValue(0);
setInputValue(0);
} else {
if (!operationSelected) {
setPreviousInputValue(inputValue);
setInputValue(0);
}
setOperationSelected(string);
}
}
}