-
Notifications
You must be signed in to change notification settings - Fork 5
/
aggregate.go
68 lines (61 loc) · 1.33 KB
/
aggregate.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
package collections
// Returns the average of all elements present in the given collection.
// This method supports only numerical types.
func Avg[V Number](c Collection[V]) V {
size := V(c.Size())
if size == 0 {
return 0
}
return Sum[V](c) / size
}
// Returns maximum element present in the given collection.
// This method supports only numerical types.
func Max[V Number](c Collection[V]) V {
slice := toSlice[V](c)
size := len(slice)
if size == 0 {
return 0
}
max := slice[0]
for i := 1; i < size; i++ {
if max < slice[i] {
max = slice[i]
}
}
return max
}
// Returns minimum element present in the given collection.
// This method supports only numerical types.
func Min[V Number](c Collection[V]) V {
slice := toSlice[V](c)
size := len(slice)
if size == 0 {
return 0
}
min := slice[0]
for i := 1; i < size; i++ {
if min > slice[i] {
min = slice[i]
}
}
return min
}
// Returns the sum of all elements present in the given collection.
// This method supports only numerical types.
func Sum[V Number](c Collection[V]) V {
slice := toSlice[V](c)
sum := V(0)
for _, elem := range slice {
sum += elem
}
return sum
}
func toSlice[V Number](c Collection[V]) []V {
switch c.Type() {
case TypeList:
return c.(*List[V]).ToArray()
case TypeSet:
return c.(*Set[V]).ToArray()
}
panic("unknown collection type")
}