-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdedupe.go
More file actions
69 lines (57 loc) · 1.54 KB
/
Copy pathdedupe.go
File metadata and controls
69 lines (57 loc) · 1.54 KB
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
// SPDX-FileCopyrightText: 2026 Comcast Cable Communications Management, LLC
// SPDX-License-Identifier: Apache-2.0
package hashy
import (
"maps"
"slices"
)
// Deduper is a utility type used to dedupe sequences of comparable values.
type Deduper[V comparable] map[V]struct{}
// Len returns the count of unique values.
func (d Deduper[V]) Len() int {
return len(d)
}
// Clear wipes out this Deduper.
func (d Deduper[V]) Clear() {
clear(d)
}
// Add adds more values to dedupe. This method will create the map as needed.
func (d *Deduper[V]) Add(more ...V) {
if *d == nil {
*d = make(Deduper[V], len(more))
}
for _, v := range more {
(*d)[v] = struct{}{}
}
}
// Slice returns a slice of this Deduper's values. The returned
// slice will not be sorted, but it will be guaranteed not to have
// duplicate values.
func (d Deduper[V]) Slice() (deduped []V) {
if d.Len() > 0 {
deduped = slices.AppendSeq(
make([]V, 0, d.Len()),
maps.Keys(d),
)
}
return
}
// AppendTo appends this Deduper's values to a given slice. The values
// are not appended in sorted order, but this method does guarantee that
// a given value will not be appended more than once.
func (d Deduper[V]) AppendTo(dst []V) []V {
if d.Len() > 0 {
dst = slices.AppendSeq(
slices.Grow(dst, d.Len()),
maps.Keys(d),
)
}
return dst
}
// SortFunc is a convenience for taking the result of Slice and sorting
// it using the supplied comparison function.
func (d Deduper[V]) SortFunc(cmp func(V, V) int) (sorted []V) {
sorted = d.Slice()
slices.SortFunc(sorted, cmp)
return
}