This repository was archived by the owner on Apr 14, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathstringutils.go
More file actions
60 lines (53 loc) · 1.63 KB
/
stringutils.go
File metadata and controls
60 lines (53 loc) · 1.63 KB
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
package stringutils
// Transform takes a slice of strings, transforms each element
// and returns a slice of strings containing the transformed values
func Transform(s []string, f func(string) string) []string {
var transformed []string
for _, e := range s {
transformed = append(transformed, f(e))
}
return transformed
}
// Quote takes a slice of strings and returns a slice
// of strings where each element of the input is put
// in double quotation marks.
func Quote(s []string) []string {
return Transform(s, func(str string) string {
return `"` + str + `"`
})
}
// DefaultIfEmpty falls back to a default value if the passed value is empty
func DefaultIfEmpty(value, defaultValue string) string {
return DefaultIf(value, defaultValue, "")
}
// DefaultIf falls back to a default value if the passed value is equal
// to the condition parameter.
func DefaultIf(value, defaultValue, condition string) string {
if value == condition {
return defaultValue
}
return value
}
// Keys extracts the key of a map[string]string and returns them
// as a slice of strings.
func Keys(m map[string]string) []string {
return Contract(m, func(k string, v string) string {
return k
})
}
// Contract takes a map[string]string and contracts pairs of key and values.
func Contract(m map[string]string, f func(string, string) string) []string {
c := make([]string, 0, len(m))
for k, v := range m {
c = append(c, f(k, v))
}
return c
}
// ErrorMessages accumulates the error messages from slice of errors.
func ErrorMessages(errs []error) []string {
ms := make([]string, 0, len(errs))
for _, err := range errs {
ms = append(ms, err.Error())
}
return ms
}