-
Notifications
You must be signed in to change notification settings - Fork 272
/
compact.go
50 lines (40 loc) · 1.1 KB
/
compact.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
package funk
import (
"reflect"
)
// Compact creates a slice with all empty/zero values removed.
func Compact(value interface{}) interface{} {
arr := redirectValue(reflect.ValueOf(value))
if arr.Kind() != reflect.Slice && arr.Kind() != reflect.Array {
panic("First parameter must be array or slice")
}
sliceElemType := sliceElem(arr.Type())
resultSliceType := reflect.SliceOf(sliceElemType)
result := reflect.MakeSlice(resultSliceType, 0, 0)
for i := 0; i < arr.Len(); i++ {
elemVal := arr.Index(i)
if elemVal.Kind() == reflect.Interface {
elemVal = elemVal.Elem()
}
redirectedElemVal := redirectValue(elemVal)
switch redirectedElemVal.Kind() {
case reflect.Invalid:
continue
case reflect.Func:
if redirectedElemVal.IsNil() {
continue
}
case reflect.Map, reflect.Slice, reflect.Chan:
if redirectedElemVal.Len() == 0 {
continue
}
default:
defaultValue := reflect.Zero(redirectedElemVal.Type()).Interface()
if redirectedElemVal.Interface() == defaultValue {
continue
}
}
result = reflect.Append(result, elemVal)
}
return result.Interface()
}