-
Notifications
You must be signed in to change notification settings - Fork 0
/
fct-calc-logic.go
111 lines (89 loc) · 1.99 KB
/
fct-calc-logic.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
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
103
104
105
106
107
108
109
110
111
/*
* Copyright (c) 2024.
* Created by Andy Pangaribuan <https://github.com/apangaribuan>.
*
* This product is protected by copyright and distributed under
* licenses restricting copying, distribution and decompilation.
* All Rights Reserved.
*/
package fct
import (
"github.com/pkg/errors"
"github.com/shopspring/decimal"
)
// supported operator: +, -, *, /, %
func calc(val ...any) (FCT, error) {
fv := FCT{
v1: "0",
v2: "0",
}
length := len(val)
if length%2 == 0 || length < 2 {
return fv, errors.New("fct calc: wrong implementation")
}
lsv := make([]any, 0)
for i := 0; i < length; i++ {
if i%2 == 0 {
vd, err := convert(val[i])
if err != nil {
return fv, err
}
lsv = append(lsv, vd)
} else {
operator, ok := isOperator(val[i])
if !ok {
return fv, errors.New("fct calc: invalid operator")
}
lsv = append(lsv, operator)
}
}
for i := 0; i < len(lsv); i++ {
if i%2 == 0 && i < len(lsv)-1 {
operator := lsv[i+1].(string)
if operator == "*" || operator == "/" || operator == "%" {
vd1 := lsv[i].(*decimal.Decimal)
vd2 := lsv[i+2].(*decimal.Decimal)
switch operator {
case "*":
val := vd1.Mul(*vd2)
lsv[i] = &val
case "/":
val := vd1.Div(*vd2)
lsv[i] = &val
case "%":
val := vd1.Mod(*vd2)
lsv[i] = &val
}
lsv = removeIndex(lsv, i+2)
lsv = removeIndex(lsv, i+1)
i--
}
}
}
for i := 0; i < len(lsv); i++ {
if i%2 == 0 && i < len(lsv)-1 {
operator := lsv[i+1].(string)
if operator == "+" || operator == "-" {
vd1 := lsv[i].(*decimal.Decimal)
vd2 := lsv[i+2].(*decimal.Decimal)
switch operator {
case "+":
val := vd1.Add(*vd2)
lsv[i] = &val
case "-":
val := vd1.Sub(*vd2)
lsv[i] = &val
}
lsv = removeIndex(lsv, i+2)
lsv = removeIndex(lsv, i+1)
i--
}
}
}
if len(lsv) != 1 {
return fv, errors.New("fct calc: something went wrong")
}
finalVal := lsv[0].(*decimal.Decimal)
fv.set(*finalVal)
return fv, nil
}