-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
subtract.go
64 lines (48 loc) · 1.11 KB
/
subtract.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
package loncha
import "sort"
type subOpt struct {
}
func mapOfExists[T comparable](slice []T) (exists map[T]bool) {
exists = map[T]bool{}
for _, v := range slice {
exists[v] = true
}
return
}
// Sub .. subtraction between two slices.
func Sub[T comparable](slice1, slice2 []T, opts ...Opt[subOpt]) (result []T) {
param, fn := MergeOpts(opts...)
defer fn(param)
exists := mapOfExists(slice2)
for _, v := range slice1 {
if _, found := exists[v]; !found {
result = append(result, v)
}
}
return
}
// SubSorted ... subtraction in sorted slice
func SubSorted[T any, V Ordered](slice1, slice2 []T, IdentFn IdentFunc[T, V]) (result []T) {
jn := 0
result = make([]T, 0, len(slice2))
for i, v := range slice1 {
key := IdentFn(slice1, i)
idx := sort.Search(len(slice2)-jn, func(j int) bool {
return IdentFn(slice2, jn+j) >= key
})
_ = v
if len(slice2) <= idx {
result = append(result, v)
break
}
// copy before idx -1
if IdentFn(slice2, idx) != key {
result = append(result, v)
}
// MENTION: required ?
if IdentFn(slice2, idx) < key {
jn = idx
}
}
return result
}