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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
|
// Package coll contains functions to help manipulate and query collections of
// data, like slices/arrays and maps.
//
// For the functions that return an array, a []interface{} is returned,
// regardless of whether or not the input was a different type.
package coll
import (
"fmt"
"reflect"
"sort"
"github.com/hairyhenderson/gomplate/conv"
"github.com/pkg/errors"
)
// Slice creates a slice from a bunch of arguments
func Slice(args ...interface{}) []interface{} {
return args
}
func interfaceSlice(slice interface{}) ([]interface{}, error) {
s := reflect.ValueOf(slice)
kind := s.Kind()
switch kind {
case reflect.Slice, reflect.Array:
ret := make([]interface{}, s.Len())
for i := 0; i < s.Len(); i++ {
ret[i] = s.Index(i).Interface()
}
return ret, nil
default:
return nil, errors.Errorf("expected an array or slice, but got a %T", s)
}
}
// Has determines whether or not a given object has a property with the given key
func Has(in interface{}, key interface{}) bool {
av := reflect.ValueOf(in)
switch av.Kind() {
case reflect.Map:
kv := reflect.ValueOf(key)
return av.MapIndex(kv).IsValid()
case reflect.Slice, reflect.Array:
l := av.Len()
for i := 0; i < l; i++ {
v := av.Index(i).Interface()
if reflect.DeepEqual(v, key) {
return true
}
}
}
return false
}
// Dict is a convenience function that creates a map with string keys.
// Provide arguments as key/value pairs. If an odd number of arguments
// is provided, the last is used as the key, and an empty string is
// set as the value.
// All keys are converted to strings, regardless of input type.
func Dict(v ...interface{}) (map[string]interface{}, error) {
dict := map[string]interface{}{}
lenv := len(v)
for i := 0; i < lenv; i += 2 {
key := conv.ToString(v[i])
if i+1 >= lenv {
dict[key] = ""
continue
}
dict[key] = v[i+1]
}
return dict, nil
}
// Keys returns the list of keys in one or more maps. The returned list of keys
// is ordered by map, each in sorted key order.
func Keys(in ...map[string]interface{}) ([]string, error) {
if len(in) == 0 {
return nil, fmt.Errorf("need at least one argument")
}
keys := []string{}
for _, m := range in {
k, _ := splitMap(m)
keys = append(keys, k...)
}
return keys, nil
}
func splitMap(m map[string]interface{}) ([]string, []interface{}) {
keys := make([]string, len(m))
values := make([]interface{}, len(m))
i := 0
for k := range m {
keys[i] = k
i++
}
sort.Strings(keys)
for i, k := range keys {
values[i] = m[k]
}
return keys, values
}
// Values returns the list of values in one or more maps. The returned list of values
// is ordered by map, each in sorted key order. If the Keys function is called with
// the same arguments, the key/value mappings will be maintained.
func Values(in ...map[string]interface{}) ([]interface{}, error) {
if len(in) == 0 {
return nil, fmt.Errorf("need at least one argument")
}
values := []interface{}{}
for _, m := range in {
_, v := splitMap(m)
values = append(values, v...)
}
return values, nil
}
// Append v to the end of list. No matter what type of input slice or array list is, a new []interface{} is always returned.
func Append(v interface{}, list interface{}) ([]interface{}, error) {
l, err := interfaceSlice(list)
if err != nil {
return nil, err
}
return append(l, v), nil
}
// Prepend v to the beginning of list. No matter what type of input slice or array list is, a new []interface{} is always returned.
func Prepend(v interface{}, list interface{}) ([]interface{}, error) {
l, err := interfaceSlice(list)
if err != nil {
return nil, err
}
return append([]interface{}{v}, l...), nil
}
// Uniq finds the unique values within list. No matter what type of input slice or array list is, a new []interface{} is always returned.
func Uniq(list interface{}) ([]interface{}, error) {
l, err := interfaceSlice(list)
if err != nil {
return nil, err
}
out := []interface{}{}
for _, v := range l {
if !Has(out, v) {
out = append(out, v)
}
}
return out, nil
}
// Reverse the list. No matter what type of input slice or array list is, a new []interface{} is always returned.
func Reverse(list interface{}) ([]interface{}, error) {
l, err := interfaceSlice(list)
if err != nil {
return nil, err
}
// nifty trick from https://github.com/golang/go/wiki/SliceTricks#reversing
for left, right := 0, len(l)-1; left < right; left, right = left+1, right-1 {
l[left], l[right] = l[right], l[left]
}
return l, nil
}
// Merge source maps (srcs) into dst. Precedence is in left-to-right order, with
// the left-most values taking precedence over the right-most.
func Merge(dst map[string]interface{}, srcs ...map[string]interface{}) (map[string]interface{}, error) {
for _, src := range srcs {
dst = mergeValues(src, dst)
}
return dst, nil
}
func copyMap(m map[string]interface{}) map[string]interface{} {
n := map[string]interface{}{}
for k, v := range m {
n[k] = v
}
return n
}
// Merges a default and override map
func mergeValues(d map[string]interface{}, o map[string]interface{}) map[string]interface{} {
def := copyMap(d)
over := copyMap(o)
for k, v := range over {
// If the key doesn't exist already, then just set the key to that value
if _, exists := def[k]; !exists {
def[k] = v
continue
}
nextMap, ok := v.(map[string]interface{})
// If it isn't another map, overwrite the value
if !ok {
def[k] = v
continue
}
// Edge case: If the key exists in the default, but isn't a map
defMap, isMap := def[k].(map[string]interface{})
// If the override map has a map for this key, prefer it
if !isMap {
def[k] = v
continue
}
// If we got to this point, it is a map in both, so merge them
def[k] = mergeValues(defMap, nextMap)
}
return def
}
// Sort a given array or slice. Uses natural sort order if possible. If a
// non-empty key is given and the list elements are maps, this will attempt to
// sort by the values of those entries.
//
// Does not modify the input list.
func Sort(key string, list interface{}) (out []interface{}, err error) {
if list == nil {
return nil, nil
}
ia, err := interfaceSlice(list)
if err != nil {
return nil, err
}
// if the types are all the same, we can sort the slice
if sameTypes(ia) {
s := make([]interface{}, len(ia))
// make a copy so the original is unmodified
copy(s, ia)
sort.SliceStable(s, func(i, j int) bool {
return lessThan(key)(s[i], s[j])
})
return s, nil
}
return ia, nil
}
// lessThan - compare two values of the same type
func lessThan(key string) func(left, right interface{}) bool {
return func(left, right interface{}) bool {
val := reflect.Indirect(reflect.ValueOf(left))
rval := reflect.Indirect(reflect.ValueOf(right))
switch val.Kind() {
case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int:
return val.Int() < rval.Int()
case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint, reflect.Uint64:
return val.Uint() < rval.Uint()
case reflect.Float32, reflect.Float64:
return val.Float() < rval.Float()
case reflect.String:
return val.String() < rval.String()
case reflect.MapOf(
reflect.TypeOf(reflect.String),
reflect.TypeOf(reflect.Interface),
).Kind():
kval := reflect.ValueOf(key)
if !val.MapIndex(kval).IsValid() {
return false
}
newleft := val.MapIndex(kval).Interface()
newright := rval.MapIndex(kval).Interface()
return lessThan("")(newleft, newright)
case reflect.Struct:
if !val.FieldByName(key).IsValid() {
return false
}
newleft := val.FieldByName(key).Interface()
newright := rval.FieldByName(key).Interface()
return lessThan("")(newleft, newright)
default:
// it's not really comparable, so...
return false
}
}
}
func sameTypes(a []interface{}) bool {
var t reflect.Type
for _, v := range a {
if t == nil {
t = reflect.TypeOf(v)
}
if reflect.ValueOf(v).Kind() != t.Kind() {
return false
}
}
return true
}
// Flatten a nested array or slice to at most 'depth' levels. Use depth of -1
// to completely flatten the input.
// Returns a new slice without modifying the input.
func Flatten(list interface{}, depth int) (out []interface{}, err error) {
l, err := interfaceSlice(list)
if err != nil {
return nil, err
}
if depth == 0 {
return l, nil
}
for _, v := range l {
s := reflect.ValueOf(v)
kind := s.Kind()
switch kind {
case reflect.Slice, reflect.Array:
vl, err := Flatten(v, depth-1)
if err != nil {
return nil, err
}
out = append(out, vl...)
default:
out = append(out, v)
}
}
return out, nil
}
|