Skip to content

Commit

Permalink
Add Sorted method
Browse files Browse the repository at this point in the history
This is a varient on `slices.Sorted` that makes it easy to get a sorted slice. This makes it easy to get the elements of the set into a sorted slice. Quite handy when using sets to build up unique elements but then needing a well defined iteration order.
  • Loading branch information
Frassle committed Sep 16, 2023
1 parent 6f5ccad commit c5522bc
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
13 changes: 13 additions & 0 deletions set.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,11 @@ SOFTWARE.
// that can enforce mutual exclusion through other means.
package mapset

import (
"cmp"

Check failure on line 39 in set.go

View workflow job for this annotation

GitHub Actions / test (1.20.1, ubuntu-latest)

package cmp is not in GOROOT (/opt/hostedtoolcache/go/1.20.1/x64/src/cmp)
"slices"

Check failure on line 40 in set.go

View workflow job for this annotation

GitHub Actions / test (1.20.1, ubuntu-latest)

package slices is not in GOROOT (/opt/hostedtoolcache/go/1.20.1/x64/src/slices)
)

// Set is the primary interface provided by the mapset package. It
// represents an unordered set of data and a large number of
// operations that can be applied to that set.
Expand Down Expand Up @@ -243,3 +248,11 @@ func NewThreadUnsafeSetFromMapKeys[T comparable, V any](val map[T]V) Set[T] {

return s
}

// Sorted returns a sorted slice of a set of any ordered type in ascending order.
// When sorting floating-point numbers, NaNs are ordered before other values.
func Sorted[E cmp.Ordered](set Set[E]) []E {
s := set.ToSlice()
slices.Sort(s)
return s
}
28 changes: 28 additions & 0 deletions set_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1298,6 +1298,34 @@ func Test_NewThreadUnsafeSetFromMapKey_Strings(t *testing.T) {
}
}

func Test_Sorted(t *testing.T) {
test := func(t *testing.T, ctor func(vals ...string) Set[string]) {
set := ctor("apple", "banana", "pear")
sorted := Sorted(set)

if len(sorted) != set.Cardinality() {
t.Errorf("Length of slice is not the same as the set. Expected: %d. Actual: %d", set.Cardinality(), len(sorted))
}

if sorted[0] != "apple" {
t.Errorf("Element 0 was not equal to apple: %s", sorted[0])
}
if sorted[1] != "banana" {
t.Errorf("Element 0 was not equal to banana: %s", sorted[1])
}
if sorted[2] != "pear" {
t.Errorf("Element 0 was not equal to pear: %s", sorted[2])
}
}

t.Run("Safe", func(t *testing.T) {
test(t, NewSet[string])
})
t.Run("Unsafe", func(t *testing.T) {
test(t, NewThreadUnsafeSet[string])
})
}

func Test_Example(t *testing.T) {
/*
requiredClasses := NewSet()
Expand Down

0 comments on commit c5522bc

Please sign in to comment.