-
Notifications
You must be signed in to change notification settings - Fork 225
/
distinct.go
98 lines (87 loc) · 2.41 KB
/
distinct.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
86
87
88
89
90
91
92
93
94
95
96
97
98
package linq
// Distinct method returns distinct elements from a collection. The result is an
// unordered collection that contains no duplicate values.
func (q Query) Distinct() Query {
return Query{
Iterate: func() Iterator {
next := q.Iterate()
set := make(map[interface{}]bool)
return func() (item interface{}, ok bool) {
for item, ok = next(); ok; item, ok = next() {
if _, has := set[item]; !has {
set[item] = true
return
}
}
return
}
},
}
}
// Distinct method returns distinct elements from a collection. The result is an
// ordered collection that contains no duplicate values.
//
// NOTE: Distinct method on OrderedQuery type has better performance than
// Distinct method on Query type.
func (oq OrderedQuery) Distinct() OrderedQuery {
return OrderedQuery{
orders: oq.orders,
Query: Query{
Iterate: func() Iterator {
next := oq.Iterate()
var prev interface{}
return func() (item interface{}, ok bool) {
for item, ok = next(); ok; item, ok = next() {
if item != prev {
prev = item
return
}
}
return
}
},
},
}
}
// DistinctBy method returns distinct elements from a collection. This method
// executes selector function for each element to determine a value to compare.
// The result is an unordered collection that contains no duplicate values.
func (q Query) DistinctBy(selector func(interface{}) interface{}) Query {
return Query{
Iterate: func() Iterator {
next := q.Iterate()
set := make(map[interface{}]bool)
return func() (item interface{}, ok bool) {
for item, ok = next(); ok; item, ok = next() {
s := selector(item)
if _, has := set[s]; !has {
set[s] = true
return
}
}
return
}
},
}
}
// DistinctByT is the typed version of DistinctBy.
//
// - selectorFn is of type "func(TSource) TSource".
//
// NOTE: DistinctBy has better performance than DistinctByT.
func (q Query) DistinctByT(selectorFn interface{}) Query {
selectorFunc, ok := selectorFn.(func(interface{}) interface{})
if !ok {
selectorGenericFunc, err := newGenericFunc(
"DistinctByT", "selectorFn", selectorFn,
simpleParamValidator(newElemTypeSlice(new(genericType)), newElemTypeSlice(new(genericType))),
)
if err != nil {
panic(err)
}
selectorFunc = func(item interface{}) interface{} {
return selectorGenericFunc.Call(item)
}
}
return q.DistinctBy(selectorFunc)
}