-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApp.js
102 lines (89 loc) · 2.94 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
94
95
96
97
98
99
100
101
102
import React, {Component} from 'react';
import {StyleSheet, Text, View} from 'react-native';
import Button from './src/components/Button';
import Display from './src/components/Display';
const initialState = {
displayValue: '0',
clearDisplay: false,
operation: null,
values: [0, 0],
current: 0,
}
export default class App extends Component {
state = { ...initialState }
addDigit = n => {
const clearDisplay = this.state.displayValue === '0'
|| this.state.clearDisplay
if (n === '.' && !clearDisplay && this.state.displayValue.includes('.')) {
return
}
const currentValue = clearDisplay ? '' : this.state.displayValue
const displayValue = currentValue + n
this.setState({displayValue, clearDisplay: false})
if (n !== '.') {
const newValue = parseFloat(displayValue)
const values = [...this.state.values]
values[this.state.current] = newValue
this.setState({ values })
}
}
clearMemory = () => {
this.setState({ ...initialState })
}
setOperation = operation => {
if (this.state.current === 0) {
this.setState({ operation, current: 1, clearDisplay: true })
} else {
const equals = operation === '='
const values = [...this.state.values]
try {
values[0] = eval(`${values[0]} ${this.state.operation} ${values[1]}`)
} catch (e) {
values[0] = this.state.values[0]
}
values[1] = 0
this.setState({
displayValue: `${values[0]}`,
operation: equals ? null : operation,
current: equals ? 0 : 1,
clearDisplay: !equals,
values,
})
}
}
render() {
return (
<View style={styles.container}>
<Display value={this.state.displayValue} />
<View style={styles.buttons}>
<Button label='AC' triple onClick={this.clearMemory} />
<Button label='/' operation onClick={this.setOperation} />
<Button label='7' onClick={this.addDigit} />
<Button label='8' onClick={this.addDigit} />
<Button label='9' onClick={this.addDigit} />
<Button label='*' operation onClick={this.setOperation} />
<Button label='4' onClick={this.addDigit} />
<Button label='5' onClick={this.addDigit} />
<Button label='6' onClick={this.addDigit} />
<Button label='-' operation onClick={this.setOperation} />
<Button label='1' onClick={this.addDigit} />
<Button label='2' onClick={this.addDigit} />
<Button label='3' onClick={this.addDigit} />
<Button label='+' operation onClick={this.setOperation} />
<Button label='0' double onClick={this.addDigit} />
<Button label='.' onClick={this.addDigit} />
<Button label='=' operation onClick={this.setOperation} />
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
buttons: {
flexDirection: 'row',
flexWrap: 'wrap',
}
});