-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
86 lines (78 loc) · 2.52 KB
/
main.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
new Vue({
el: '#app',
data: {
equation: '0',
isDecimalAdded: false,
isOperatorAdded: false,
isStarted: false,
},
methods: {
// Check if the character is + / - / × / ÷
isOperator(character) {
return ['+', '-', '×', '÷'].indexOf(character) > -1
},
// When pressed Operators or Numbers
append(character) {
// Start
if (this.equation === '0' && !this.isOperator(character)) {
if (character === '.') {
this.equation += '' + character
this.isDecimalAdded = true
} else {
this.equation = '' + character
}
this.isStarted = true
return
}
// If Number
if (!this.isOperator(character)) {
if (character === '.' && this.isDecimalAdded) {
return
}
if (character === '.') {
this.isDecimalAdded = true
this.isOperatorAdded = true
} else {
this.isOperatorAdded = false
}
this.equation += '' + character
}
// Added Operator
if (this.isOperator(character) && !this.isOperatorAdded) {
this.equation += '' + character
this.isDecimalAdded = false
this.isOperatorAdded = true
}
},
// When pressed '='
calculate() {
let result = this.equation.replace(new RegExp('×', 'g'), '*').replace(new RegExp('÷', 'g'), '/')
this.equation = parseFloat(eval(result).toFixed(9)).toString()
this.isDecimalAdded = false
this.isOperatorAdded = false
},
// When pressed '+/-'
calculateToggle() {
if (this.isOperatorAdded || !this.isStarted) {
return
}
this.equation = this.equation + '* -1'
this.calculate()
},
// When pressed '%'
calculatePercentage() {
if (this.isOperatorAdded || !this.isStarted) {
return
}
this.equation = this.equation + '* 0.01'
this.calculate()
},
// When pressed 'AC'
clear() {
this.equation = '0'
this.isDecimalAdded = false
this.isOperatorAdded = false
this.isStarted = false
}
}
})