-
Notifications
You must be signed in to change notification settings - Fork 1
/
distinct.go
81 lines (68 loc) · 1.86 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
package flinx
import "github.com/kom0055/go-flinx/hashset"
// Distinct method returns distinct elements from a collection. The result is an
// unordered collection that contains no duplicate values.
func Distinct[T comparable](q Query[T]) Query[T] {
return Query[T]{
Iterate: func() Iterator[T] {
next := q.Iterate()
set := hashset.NewAny[T]()
return func() (item T, ok bool) {
for item, ok = next(); ok; item, ok = next() {
if !set.Has(item) {
set.Insert(item)
return
}
}
return
}
},
}
}
// DistinctOrderedQuery method returns distinct elements from a collection. The result is an
// ordered collection that contains no duplicate values.
//
// NOTE: DistinctOrderedQuery method on OrderedQuery type has better performance than
// Distinct method on Query type.
func DistinctOrderedQuery[T comparable](oq OrderedQuery[T]) OrderedQuery[T] {
return OrderedQuery[T]{
Query: Query[T]{
Iterate: func() Iterator[T] {
next := oq.Iterate()
var prev T
return func() (item T, 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 DistinctBy[T any, V comparable](selector func(T) V) func(q Query[T]) Query[T] {
return func(q Query[T]) Query[T] {
return Query[T]{
Iterate: func() Iterator[T] {
next := q.Iterate()
set := hashset.NewAny[V]()
return func() (item T, ok bool) {
for item, ok = next(); ok; item, ok = next() {
s := selector(item)
if !set.Has(s) {
set.Insert(s)
return
}
}
return
}
},
}
}
}