From c5522bcca9c70f75f8248ac23cea2130bbbf53a5 Mon Sep 17 00:00:00 2001 From: Fraser Waters Date: Sat, 16 Sep 2023 22:31:43 +0100 Subject: [PATCH] Add Sorted method 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. --- set.go | 13 +++++++++++++ set_test.go | 28 ++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/set.go b/set.go index 4c52c8e..6f0b971 100644 --- a/set.go +++ b/set.go @@ -35,6 +35,11 @@ SOFTWARE. // that can enforce mutual exclusion through other means. package mapset +import ( + "cmp" + "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. @@ -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 +} diff --git a/set_test.go b/set_test.go index 23e8f09..b7a347f 100644 --- a/set_test.go +++ b/set_test.go @@ -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()