-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsum.go
73 lines (62 loc) · 1.44 KB
/
sum.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
package dovetail
import (
"encoding/json"
"fmt"
"github.com/project-flogo/core/data"
"github.com/project-flogo/core/data/expression/function"
"github.com/project-flogo/core/support/log"
"strconv"
"reflect"
"math"
)
// Sum dummy struct
type Sum struct {
}
func init() {
function.Register(&Sum{})
}
// Name of function
func (s *Sum) Name() string {
return "sum"
}
// Sig - function signature
func (s *Sum) Sig() (paramTypes []data.Type, isVariadic bool) {
return []data.Type{data.TypeAny}, false
}
// Eval - function implementation
func (s *Sum) Eval(params ...interface{}) (interface{}, error) {
log.RootLogger().Debugf("Start sum function with param %+v", params[0])
items := reflect.ValueOf(params[0])
if items.Kind() != reflect.Slice {
return nil, fmt.Errorf("param %T is not an array", params[0])
}
total := 0.0
for i := 0; i < items.Len(); i++ {
val := items.Index(i).Interface()
if v, err := coerceToFloat(val); err == nil {
if !math.IsNaN(v) && !math.IsInf(v, 0) {
total += v
}
}
}
return total, nil
}
func coerceToFloat(val interface{}) (float64, error) {
switch t := val.(type) {
case int:
return float64(t), nil
case int64:
return float64(t), nil
case float64:
return float64(t), nil
case json.Number:
i, err := t.Float64()
return float64(i), err
case string:
return strconv.ParseFloat(t, 64)
case nil:
return 0.0, nil
default:
return 0.0, fmt.Errorf("Unable to coerce %#v to float64", val)
}
}