-
Notifications
You must be signed in to change notification settings - Fork 225
/
intersect.go
87 lines (75 loc) · 2.17 KB
/
intersect.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
package linq
// Intersect produces the set intersection of the source collection and the
// provided input collection. The intersection of two sets A and B is defined as
// the set that contains all the elements of A that also appear in B, but no
// other elements.
func (q Query) Intersect(q2 Query) Query {
return Query{
Iterate: func() Iterator {
next := q.Iterate()
next2 := q2.Iterate()
set := make(map[interface{}]bool)
for item, ok := next2(); ok; item, ok = next2() {
set[item] = true
}
return func() (item interface{}, ok bool) {
for item, ok = next(); ok; item, ok = next() {
if _, has := set[item]; has {
delete(set, item)
return
}
}
return
}
},
}
}
// IntersectBy produces the set intersection of the source collection and the
// provided input collection. The intersection of two sets A and B is defined as
// the set that contains all the elements of A that also appear in B, but no
// other elements.
//
// IntersectBy invokes a transform function on each element of both collections.
func (q Query) IntersectBy(q2 Query,
selector func(interface{}) interface{}) Query {
return Query{
Iterate: func() Iterator {
next := q.Iterate()
next2 := q2.Iterate()
set := make(map[interface{}]bool)
for item, ok := next2(); ok; item, ok = next2() {
s := selector(item)
set[s] = true
}
return func() (item interface{}, ok bool) {
for item, ok = next(); ok; item, ok = next() {
s := selector(item)
if _, has := set[s]; has {
delete(set, s)
return
}
}
return
}
},
}
}
// IntersectByT is the typed version of IntersectBy.
//
// - selectorFn is of type "func(TSource) TSource"
//
// NOTE: IntersectBy has better performance than IntersectByT.
func (q Query) IntersectByT(q2 Query,
selectorFn interface{}) Query {
selectorGenericFunc, err := newGenericFunc(
"IntersectByT", "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.IntersectBy(q2, selectorFunc)
}