Skip to content

Commit 0045f23

Browse files
committed
Add Set.SortedSliceFunc
1 parent 3269f08 commit 0045f23

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

set/set.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -183,3 +183,15 @@ func SortedSlice[E constraints.Ordered](set Set[E]) []E {
183183
})
184184
return res
185185
}
186+
187+
// SortedSliceFunc takes a Set and converts it to a slice, sorting it by less.
188+
func SortedSliceFunc[E comparable](set Set[E], less func(e1, e2 E) bool) []E {
189+
res := make([]E, 0, len(set))
190+
for item := range set {
191+
res = append(res, item)
192+
}
193+
sort.Slice(res, func(i, j int) bool {
194+
return less(res[i], res[j])
195+
})
196+
return res
197+
}

set/set_test.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,4 +168,12 @@ var _ = Describe("Set", func() {
168168
Expect(SortedSlice(s)).To(Equal([]int{1, 3, 5, 7, 10}))
169169
})
170170
})
171+
172+
Describe("SortedSliceFunc", func() {
173+
It("should return an ordered slice of the items depending on the less function", func() {
174+
s := New[int](5, 1, 10, 7, 3)
175+
176+
Expect(SortedSliceFunc(s, func(v1, v2 int) bool { return v1 > v2 })).To(Equal([]int{10, 7, 5, 3, 1}))
177+
})
178+
})
171179
})

0 commit comments

Comments
 (0)