Skip to content

Commit 7741a0f

Browse files
zonewaveshoenig
authored andcommitted
fix(treeset): fix RemoveFunc not remove all matched node (#63)
1. add a filterSlice method that returns the elements of s that satisfy the predicate as a slice, in order. 2. first find remove ids by filterSlice, secondly to remove by removeSlice
1 parent a6b8759 commit 7741a0f

2 files changed

Lines changed: 18 additions & 13 deletions

File tree

examples_treeset_test.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -157,20 +157,20 @@ func ExampleTreeSet_RemoveSet() {
157157
}
158158

159159
func ExampleTreeSet_RemoveFunc() {
160-
s := TreeSetFrom[int, Compare[int]]([]int{1, 2, 3, 4, 5, 6, 7, 8, 9}, Cmp[int])
160+
s := TreeSetFrom[int, Compare[int]](ints(20), Cmp[int])
161161

162162
fmt.Println(s)
163163

164164
even := func(i int) bool {
165-
return i%2 == 0
165+
return i%3 != 0
166166
}
167167
s.RemoveFunc(even)
168168

169169
fmt.Println(s)
170170

171171
// Output:
172-
// [1 2 3 4 5 6 7 8 9]
173-
// [1 3 5 7 9]
172+
// [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20]
173+
// [3 6 9 12 15 18]
174174
}
175175

176176
func ExampleTreeSet_Contains() {

treeset.go

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -154,15 +154,8 @@ func (s *TreeSet[T, C]) RemoveSet(o *TreeSet[T, C]) bool {
154154
//
155155
// Return true if s was modified, false otherwise.
156156
func (s *TreeSet[T, C]) RemoveFunc(f func(T) bool) bool {
157-
modified := false
158-
remove := func(item T) bool {
159-
if f(item) && s.Remove(item) {
160-
modified = true
161-
}
162-
return true
163-
}
164-
s.ForEach(remove)
165-
return modified
157+
removeIds := s.FilterSlice(f)
158+
return s.RemoveSlice(removeIds)
166159
}
167160

168161
// Min returns the smallest item in the set.
@@ -356,6 +349,18 @@ func (s *TreeSet[T, C]) Slice() []T {
356349
return result
357350
}
358351

352+
// FilterSlice returns the elements of s that satisfy the predicate f.
353+
func (s *TreeSet[T, C]) FilterSlice(filter func(T) bool) []T {
354+
result := make([]T, 0, s.Size())
355+
s.ForEach(func(t T) bool {
356+
if filter != nil && filter(t) {
357+
result = append(result, t)
358+
}
359+
return true
360+
})
361+
return result
362+
}
363+
359364
// Subset returns whether o is a subset of s.
360365
func (s *TreeSet[T, C]) Subset(o *TreeSet[T, C]) bool {
361366
// try the fast paths

0 commit comments

Comments
 (0)