-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathApp.js
More file actions
65 lines (56 loc) · 1.79 KB
/
App.js
File metadata and controls
65 lines (56 loc) · 1.79 KB
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
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { Constants } from 'expo';
import ExpressionBox from './components/ExpressionBox.js';
import ResultBox from './components/ResultBox.js';
import NumPad from './components/NumPad.js';
// We are using math.js library to calculate results from any string expression
const math = require('mathjs');
export default class App extends React.Component {
constructor(props){
super(props);
this.state = {lastexpression: [], expression: '', result: ''}
this._assembleExpression = this._assembleExpression.bind(this);
this._calculateResult = this._calculateResult.bind(this);
this._rollbackExpression = this._rollbackExpression.bind(this);
}
_rollbackExpression() {
this.state.expression && this.setState((prevState) => ({
expression: prevState.lastexpression.pop(),
lastexpression: prevState.lastexpression
}));
}
_assembleExpression(symbol) {
this.setState((prevState) => ({
lastexpression: [...prevState.lastexpression, prevState.expression],
expression: prevState.expression + symbol
}));
}
_calculateResult() {
let result;
try {
result = math.eval(this.state.expression);
} catch (e) {
result = 'Error';
}
this.setState({result: result});
}
render() {
return (
<View style={styles.container}>
<ExpressionBox expression={this.state.expression}/>
<ResultBox result={this.state.result}/>
<NumPad
assembleExpression={this._assembleExpression}
calculateResult={this._calculateResult}
deletePressed={this._rollbackExpression}/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
paddingTop: Constants.statusBarHeight,
},
});