-
Notifications
You must be signed in to change notification settings - Fork 1
/
difference.go
49 lines (39 loc) · 1.34 KB
/
difference.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
package array
import (
"reflect"
"github.com/warriors-vn/go-dash/constants"
)
// Difference returns a new Slice that contains the elements from the input array that are not present in the exclude slices.
// It takes an array-like data structure and one or more exclude slices.
// The function returns the new Slice of different elements and an error if any occurs.
func Difference(array interface{}, exclude ...interface{}) (interface{}, error) {
arrValue := reflect.ValueOf(array)
if arrValue.Kind() != reflect.Slice && arrValue.Kind() != reflect.Array {
return nil, constants.ErrNotSlice
}
var excludeArr interface{}
if exclude == nil {
return array, nil
} else {
excludeArr = exclude[0]
}
excludeValue := reflect.ValueOf(excludeArr)
if excludeValue.Kind() != reflect.Slice && arrValue.Kind() != reflect.Array {
return nil, constants.ErrNotSlice
}
if excludeValue.Len() == 0 || arrValue.Len() == 0 {
return array, nil
}
mapExcludeValue := make(map[interface{}]int)
for i := 0; i < excludeValue.Len(); i++ {
mapExcludeValue[excludeValue.Index(i).Interface()]++
}
result := reflect.MakeSlice(arrValue.Type(), 0, 0)
for i := 0; i < arrValue.Len(); i++ {
element := arrValue.Index(i)
if _, ok := mapExcludeValue[element.Interface()]; !ok {
result = reflect.Append(result, element)
}
}
return result.Interface(), nil
}