sets: convert set types to generics (#3519)

* sets: convert set types to generics

* sets: use internal sets package
This commit is contained in:
Caleb Doxsey 2022-07-29 12:32:17 -06:00 committed by GitHub
parent 92a9251cde
commit b5ac7dbc76
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
9 changed files with 61 additions and 54 deletions

View file

@ -1,59 +1,65 @@
package sets
import "github.com/google/btree"
import (
"github.com/google/btree"
"golang.org/x/exp/constraints"
)
func lessFn(a, b string) bool { return a < b }
// A SortedString is a set of strings with sorted iteration.
type SortedString struct {
b *btree.BTreeG[string]
// A Sorted is a set with sorted iteration.
type Sorted[T any] struct {
b *btree.BTreeG[T]
less func(a, b T) bool
}
// NewSortedString creates a new sorted string set.
func NewSortedString() *SortedString {
return &SortedString{
b: btree.NewG[string](8, lessFn),
// NewSorted creates a new sorted string set.
func NewSorted[T constraints.Ordered]() *Sorted[T] {
less := func(a, b T) bool {
return a < b
}
return &Sorted[T]{
b: btree.NewG(8, less),
less: less,
}
}
// Add adds a string to the set.
func (s *SortedString) Add(elements ...string) {
func (s *Sorted[T]) Add(elements ...T) {
for _, element := range elements {
s.b.ReplaceOrInsert(element)
}
}
// Clear clears the set.
func (s *SortedString) Clear() {
s.b = btree.NewG[string](8, lessFn)
func (s *Sorted[T]) Clear() {
s.b = btree.NewG(8, s.less)
}
// Delete deletes an element from the set.
func (s *SortedString) Delete(element string) {
func (s *Sorted[T]) Delete(element T) {
s.b.Delete(element)
}
// ForEach iterates over the set in ascending order.
func (s *SortedString) ForEach(callback func(element string) bool) {
s.b.Ascend(func(item string) bool {
func (s *Sorted[T]) ForEach(callback func(element T) bool) {
s.b.Ascend(func(item T) bool {
return callback(item)
})
}
// Has returns true if the elment is in the set.
func (s *SortedString) Has(element string) bool {
func (s *Sorted[T]) Has(element T) bool {
return s.b.Has(element)
}
// Size returns the size of the set.
func (s *SortedString) Size() int {
func (s *Sorted[T]) Size() int {
return s.b.Len()
}
// ToSlice returns a slice of all the elements in the set.
func (s *SortedString) ToSlice() []string {
arr := make([]string, 0, s.Size())
s.b.Ascend(func(item string) bool {
func (s *Sorted[T]) ToSlice() []T {
arr := make([]T, 0, s.Size())
s.b.Ascend(func(item T) bool {
arr = append(arr, item)
return true
})