-
Notifications
You must be signed in to change notification settings - Fork 3
/
uniq.go
50 lines (47 loc) · 1.03 KB
/
uniq.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 fp
import "reflect"
func (q *stream) Uniq() Stream {
var iter iterator
return newStream(newCtx(q.ctx), q.expectElemTyp, func() (reflect.Value, bool) {
if iter == nil {
dup := make(map[interface{}]struct{})
iter = func() (reflect.Value, bool) {
for {
val, ok := q.iter()
if !ok {
return val, false
}
key := val.Interface()
if _, ok := dup[key]; !ok {
dup[key] = struct{}{}
return val, true
}
}
}
}
return iter()
})
}
func (q *stream) UniqBy(fn interface{}) Stream {
var iter iterator
return newStream(newCtx(q.ctx), q.expectElemTyp, func() (reflect.Value, bool) {
if iter == nil {
getKey := reflect.ValueOf(fn)
dup := make(map[interface{}]struct{})
iter = func() (reflect.Value, bool) {
for {
val, ok := q.iter()
if !ok {
return val, false
}
key := getKey.Call([]reflect.Value{val})[0].Interface()
if _, ok := dup[key]; !ok {
dup[key] = struct{}{}
return val, true
}
}
}
}
return iter()
})
}