forked from milosgajdos/gosom
/
utils.go
59 lines (55 loc) · 1.61 KB
/
utils.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
package utils
import (
"strconv"
"strings"
)
// ParseDims expects a string that contains comma-separated integer values.
// It tries to convert the parameters to their numerical values and returns them.
// If empty string is supplied, it allocates 2-dims slice and returns it.
// It returns error if a non-empty string is passed in as a parameter and
// the values it contains can not be converted to integers.
func ParseDims(dimString string) ([]int, error) {
var intDims []int
// if empty string, return empty slice
if dimString == "" {
intDims = make([]int, 2)
return intDims, nil
}
// parse non-empty string into int slice
strDims := strings.Split(dimString, ",")
for _, strDim := range strDims {
intDim, err := strconv.Atoi(strDim)
if err != nil {
return nil, err
}
intDims = append(intDims, intDim)
}
return intDims, nil
}
// IntProduct calculates a product of all items in slice passed in as a parameter
// It returns 1.0 if the slice is nil or empty.
func IntProduct(vector []int) int {
if len(vector) == 0 || vector == nil {
return 1
}
product := 1
for _, v := range vector {
product = product * v
}
return product
}
// IntCumProduct calculates a cumulative product of all items in slice as a parameter
// and returns it in a new slice. The origin slice remains unmodified
// It returns empty slice if either the supplied slice is empty or nil
func IntCumProduct(vector []int) []int {
cumProd := []int{}
if len(vector) == 0 || vector == nil {
return cumProd
}
partProd := 1
for _, val := range vector {
partProd = partProd * val
cumProd = append(cumProd, partProd)
}
return cumProd
}