/
duplicates.go
67 lines (59 loc) · 1.67 KB
/
duplicates.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
package duplicates
import (
"github.com/wesovilabs/koazee/errors"
"reflect"
)
// OpCode identifier for operation RemoveDuplicates
const OpCode = "removeDuplicates"
// RemoveDuplicates structure
type RemoveDuplicates struct {
ItemsValue reflect.Value
ItemsType reflect.Type
}
// Run performs the operation
func (op *RemoveDuplicates) Run() (reflect.Value, *errors.Error) {
if err := op.validate(); err != nil {
return reflect.ValueOf(nil), err
}
keys := op.prepareMapWithKeys()
if op.ItemsValue.Index(0).Kind() == reflect.Ptr {
newItems := reflect.MakeSlice(reflect.SliceOf(op.ItemsType), 0, 0)
for index := 0; index < op.ItemsValue.Len(); index++ {
val := op.ItemsValue.Index(index).Elem().Interface()
if keys[val] == 0 {
continue
}
keys[val] = 0
newItems = reflect.Append(newItems, op.ItemsValue.Index(index))
}
return newItems, nil
}
newItems := reflect.MakeSlice(reflect.SliceOf(op.ItemsType), 0, 0)
for index := 0; index < op.ItemsValue.Len(); index++ {
val := op.ItemsValue.Index(index).Interface()
if keys[val] == 0 {
continue
}
keys[val] = 0
newItems = reflect.Append(newItems, op.ItemsValue.Index(index))
}
return newItems, nil
}
func (op *RemoveDuplicates) validate() *errors.Error {
return nil
}
func (op *RemoveDuplicates) prepareMapWithKeys() map[interface{}]int {
keys := make(map[interface{}]int)
if op.ItemsValue.Index(0).Kind() == reflect.Ptr {
for index := 0; index < op.ItemsValue.Len(); index++ {
v := op.ItemsValue.Index(index).Elem().Interface()
keys[v]++
}
} else {
for index := 0; index < op.ItemsValue.Len(); index++ {
v := op.ItemsValue.Index(index).Interface()
keys[v]++
}
}
return keys
}