/
slices.go
85 lines (71 loc) · 2.16 KB
/
slices.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
package utils
import (
"reflect"
"sort"
)
func AppendEmptySliceField(slice reflect.Value) reflect.Value {
newField := reflect.Zero(slice.Type().Elem())
return reflect.Append(slice, newField)
}
func SetSliceLengh(slice reflect.Value, length int) reflect.Value {
if length > slice.Len() {
for i := slice.Len(); i < length; i++ {
slice = AppendEmptySliceField(slice)
}
} else if length < slice.Len() {
slice = slice.Slice(0, length)
}
return slice
}
func DeleteEmptySliceElementsVal(sliceVal reflect.Value) reflect.Value {
if sliceVal.Kind() != reflect.Slice {
panic("Argument is not a slice: " + sliceVal.String())
}
zeroVal := reflect.Zero(sliceVal.Type().Elem())
for i := 0; i < sliceVal.Len(); i++ {
elemVal := sliceVal.Index(i)
if reflect.DeepEqual(elemVal.Interface(), zeroVal.Interface()) {
before := sliceVal.Slice(0, i)
after := sliceVal.Slice(i+1, sliceVal.Len())
sliceVal = reflect.AppendSlice(before, after)
i--
}
}
return sliceVal
}
func DeleteEmptySliceElements(slice interface{}) interface{} {
return DeleteEmptySliceElementsVal(reflect.ValueOf(slice)).Interface()
}
func DeleteSliceElementVal(sliceVal reflect.Value, idx int) reflect.Value {
if idx < 0 || idx >= sliceVal.Len() {
return sliceVal
}
before := sliceVal.Slice(0, idx)
after := sliceVal.Slice(idx+1, sliceVal.Len())
sliceVal = reflect.AppendSlice(before, after)
return sliceVal
}
func DeleteSliceElement(slice interface{}, idx int) interface{} {
return DeleteSliceElementVal(reflect.ValueOf(slice), idx).Interface()
}
// Implements sort.Interface
type SortableInterfaceSlice struct {
Slice []interface{}
LessFunc func(a, b interface{}) bool
}
func (self *SortableInterfaceSlice) Len() int {
return len(self.Slice)
}
func (self *SortableInterfaceSlice) Less(i, j int) bool {
return self.LessFunc(self.Slice[i], self.Slice[j])
}
func (self *SortableInterfaceSlice) Swap(i, j int) {
self.Slice[i], self.Slice[j] = self.Slice[j], self.Slice[i]
}
func (self *SortableInterfaceSlice) Sort() {
sort.Sort(self)
}
func SortInterfaceSlice(slice []interface{}, lessFunc func(a, b interface{}) bool) {
sortable := SortableInterfaceSlice{slice, lessFunc}
sortable.Sort()
}