-
Notifications
You must be signed in to change notification settings - Fork 0
/
calculator.go
72 lines (67 loc) · 1.25 KB
/
calculator.go
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
// calculator project calculator.go
package calculator
import (
"fmt"
"strconv"
"strings"
)
const (
PLUS = "+"
MINUS = "-"
MULTIPLY = "*"
DIVIDE = "/"
)
func NewOp(op string) func(a int, b int) float64 {
switch op {
case PLUS:
return func(a int, b int) float64 {
return a + b
}
case MINUS:
return func(a int, b int) float64 {
return a - b
}
case MULTIPLY:
return func(a int, b int) float64 {
return a * b
}
case DIVIDE:
return func(a int, b int) float64 {
return a / b
}
default:
panic(fmt.Sprintf("Not such function %v", op))
}
}
func Calculate(expr string) float64 {
// remove spaces
expr = strings.Replace(expr, " ", "", -1)
// build tree
opTree := buildTree(expr)
// calculate
return calculate(opTree)
}
func calculate(tree *opTree) float64 {
if tree.typ == leaf {
ret, err := strconv.ParseFloat(tree.value, 64)
if err != nil {
panic(err)
} else {
return ret
}
}
leftRes := calculate(tree.left)
rightRes := calculate(tree.right)
switch tree.value {
case PLUS:
return leftRes + rightRes
case MINUS:
return leftRes - rightRes
case MULTIPLY:
return leftRes * rightRes
case DIVIDE:
return leftRes / rightRes
default:
panic(fmt.Sprintf("Invalid operation %v", tree.value))
}
}