-
Notifications
You must be signed in to change notification settings - Fork 18
/
strings.go
91 lines (82 loc) · 1.76 KB
/
strings.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
package stringutils
import (
"reflect"
"sort"
)
func ContainsString(s string, slice []string) bool {
for _, s2 := range slice {
if s2 == s {
return true
}
}
return false
}
// Returns true if slice strings contains any of the strings.
func ContainsAny(strings []string, slice []string) bool {
for _, s := range strings {
if ContainsString(s, slice) {
return true
}
}
return false
}
func ContainsMap(maps []map[string]string, item map[string]string) bool {
for _, m := range maps {
if reflect.DeepEqual(m, item) {
return true
}
}
return false
}
func KeysAndValues(m map[string]string) ([]string, []string) {
var keys []string
for k := range m {
keys = append(keys, k)
}
sort.Strings(keys)
var values []string
for _, k := range keys {
values = append(values, m[k])
}
return keys, values
}
func Keys(m map[string]interface{}) []string {
var keys []string
for k := range m {
keys = append(keys, k)
}
sort.Strings(keys)
return keys
}
func Unique(stringSlice []string) []string {
keys := make(map[string]bool)
list := []string{}
for _, entry := range stringSlice {
if _, value := keys[entry]; !value {
keys[entry] = true
list = append(list, entry)
}
}
return list
}
func StringSliceToHashSet(stringSlice []string) map[string]bool {
if len(stringSlice) == 0 {
return nil
}
set := make(map[string]bool)
for _, s := range stringSlice {
set[s] = true
}
return set
}
// returns a new array where f is applied on all values in stringSlice
// usage:
// fmt.Println(MapStringSlice([]string{"abc","def"}, strings.ToUpper)
// result: []string{"ABC", "DEF}
func MapStringSlice(stringSlice []string, f func(string) string) []string {
out := make([]string, len(stringSlice))
for i, v := range stringSlice {
out[i] = f(v)
}
return out
}