@@ -6,20 +6,40 @@ class App extends React.Component {
6
6
constructor ( ) {
7
7
super ( )
8
8
this . state = {
9
- calculationText : ""
9
+ calculationText : "" ,
10
+ resultText : ''
10
11
}
12
+ this . operation = [ 'Del' , '+' , '-' , '*' , '/' ] ;
11
13
}
12
14
13
15
calculateResult ( ) {
14
16
const text = this . state . calculationText
17
+ console . log ( text , eval ( text ) )
18
+ this . setState ( {
19
+ resultText : eval ( text )
20
+ } )
21
+ //BODMAS
22
+ // eval(text)
15
23
// now parse this text
16
24
}
17
25
26
+ validate ( ) {
27
+ const text = this . state . calculationText
28
+ switch ( text . slice ( - 1 ) ) {
29
+ case '+' :
30
+ case '-' :
31
+ case '*' :
32
+ case '/' :
33
+ return false
34
+ }
35
+ return true
36
+ }
37
+
18
38
buttonbPressed ( text ) {
19
39
//console.log(text)
20
40
21
41
if ( text == '=' ) {
22
- return this . calculateResult ( )
42
+ return this . validate ( ) && this . calculateResult ( )
23
43
}
24
44
this . setState ( {
25
45
calculationText : this . state . calculationText + text
@@ -31,10 +51,22 @@ class App extends React.Component {
31
51
case 'Del' :
32
52
let text = this . state . calculationText . split ( '' )
33
53
text . pop ( )
34
-
35
54
this . setState ( {
36
55
calculationText : text . join ( '' )
37
56
} )
57
+ break ;
58
+ case '+' :
59
+ case '-' :
60
+ case '*' :
61
+ case '/' :
62
+ const lastChar = this . state . calculationText . split ( '' ) . pop ( )
63
+
64
+ if ( this . operation . indexOf ( lastChar ) > 0 ) return
65
+
66
+ if ( this . state . text == "" ) return
67
+ this . setState ( {
68
+ calculationText : this . state . calculationText + operation
69
+ } )
38
70
}
39
71
}
40
72
@@ -54,11 +86,10 @@ class App extends React.Component {
54
86
}
55
87
56
88
let oper = [ ] ;
57
- let operation = [ 'Del' , '+' , '-' , '*' , '/' ] ;
58
- for ( let i = 0 ; i < 4 ; i ++ ) {
89
+ for ( let i = 0 ; i < 5 ; i ++ ) {
59
90
oper . push (
60
- < TouchableOpacity style = { styles . btn } onPress = { ( ) => this . operate ( operation [ i ] ) } >
61
- < Text style = { [ styles . btnText , { color : 'white' } ] } > { operation [ i ] } </ Text >
91
+ < TouchableOpacity style = { styles . btn } onPress = { ( ) => this . operate ( this . operation [ i ] ) } >
92
+ < Text style = { [ styles . btnText , { color : 'white' } ] } > { this . operation [ i ] } </ Text >
62
93
</ TouchableOpacity >
63
94
)
64
95
}
@@ -68,7 +99,7 @@ class App extends React.Component {
68
99
< Text style = { styles . calculationText } > { this . state . calculationText } </ Text >
69
100
</ View >
70
101
< View style = { styles . result } >
71
- < Text style = { styles . resultText } > 121 </ Text >
102
+ < Text style = { styles . resultText } > { this . state . resultText } </ Text >
72
103
</ View >
73
104
< View style = { styles . buttons } >
74
105
< View style = { styles . numbers } >
0 commit comments