Skip to content

Commit

Permalink
fix(treeset): fix RemoveFunc not remove all matched node (#63)
Browse files Browse the repository at this point in the history
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
  • Loading branch information
zonewave authored and shoenig committed May 13, 2023
1 parent a6b8759 commit 7741a0f
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 13 deletions.
8 changes: 4 additions & 4 deletions examples_treeset_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -157,20 +157,20 @@ func ExampleTreeSet_RemoveSet() {
}

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

fmt.Println(s)

even := func(i int) bool {
return i%2 == 0
return i%3 != 0
}
s.RemoveFunc(even)

fmt.Println(s)

// Output:
// [1 2 3 4 5 6 7 8 9]
// [1 3 5 7 9]
// [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20]
// [3 6 9 12 15 18]
}

func ExampleTreeSet_Contains() {
Expand Down
23 changes: 14 additions & 9 deletions treeset.go
Original file line number Diff line number Diff line change
Expand Up @@ -154,15 +154,8 @@ func (s *TreeSet[T, C]) RemoveSet(o *TreeSet[T, C]) bool {
//
// Return true if s was modified, false otherwise.
func (s *TreeSet[T, C]) RemoveFunc(f func(T) bool) bool {
modified := false
remove := func(item T) bool {
if f(item) && s.Remove(item) {
modified = true
}
return true
}
s.ForEach(remove)
return modified
removeIds := s.FilterSlice(f)
return s.RemoveSlice(removeIds)
}

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

// FilterSlice returns the elements of s that satisfy the predicate f.
func (s *TreeSet[T, C]) FilterSlice(filter func(T) bool) []T {
result := make([]T, 0, s.Size())
s.ForEach(func(t T) bool {
if filter != nil && filter(t) {
result = append(result, t)
}
return true
})
return result
}

// Subset returns whether o is a subset of s.
func (s *TreeSet[T, C]) Subset(o *TreeSet[T, C]) bool {
// try the fast paths
Expand Down

0 comments on commit 7741a0f

Please sign in to comment.