github.com/songzhibin97/go-baseutils@v0.0.2-0.20240302024150-487d8ce9c082/structure/sets/treeset/enumerable.go (about) 1 package treeset 2 3 import ( 4 "github.com/songzhibin97/go-baseutils/structure/containers" 5 "github.com/songzhibin97/go-baseutils/structure/trees/redblacktree" 6 ) 7 8 // Assert Enumerable implementation 9 var _ containers.EnumerableWithIndex[any] = (*Set[any])(nil) 10 11 // Each calls the given function once for each element, passing that element's index and value. 12 func (set *Set[E]) Each(f func(index int, value E)) { 13 iterator := set.Iterator() 14 for iterator.Next() { 15 f(iterator.Index(), iterator.Value()) 16 } 17 } 18 19 // Map invokes the given function once for each element and returns a 20 // container containing the values returned by the given function. 21 func (set *Set[E]) Map(f func(index int, value E) E) *Set[E] { 22 newSet := &Set[E]{tree: redblacktree.NewWith[E, struct{}](set.tree.Comparator)} 23 iterator := set.Iterator() 24 for iterator.Next() { 25 newSet.Add(f(iterator.Index(), iterator.Value())) 26 } 27 return newSet 28 } 29 30 // Select returns a new container containing all elements for which the given function returns a true value. 31 func (set *Set[E]) Select(f func(index int, value E) bool) *Set[E] { 32 newSet := &Set[E]{tree: redblacktree.NewWith[E, struct{}](set.tree.Comparator)} 33 iterator := set.Iterator() 34 for iterator.Next() { 35 if f(iterator.Index(), iterator.Value()) { 36 newSet.Add(iterator.Value()) 37 } 38 } 39 return newSet 40 } 41 42 // Any passes each element of the container to the given function and 43 // returns true if the function ever returns true for any element. 44 func (set *Set[E]) Any(f func(index int, value E) bool) bool { 45 iterator := set.Iterator() 46 for iterator.Next() { 47 if f(iterator.Index(), iterator.Value()) { 48 return true 49 } 50 } 51 return false 52 } 53 54 // All passes each element of the container to the given function and 55 // returns true if the function returns true for all elements. 56 func (set *Set[E]) All(f func(index int, value E) bool) bool { 57 iterator := set.Iterator() 58 for iterator.Next() { 59 if !f(iterator.Index(), iterator.Value()) { 60 return false 61 } 62 } 63 return true 64 } 65 66 // Find passes each element of the container to the given function and returns 67 // the first (index,value) for which the function is true or -1,nil otherwise 68 // if no element matches the criteria. 69 func (set *Set[E]) Find(f func(index int, value E) bool) (int, E) { 70 iterator := set.Iterator() 71 for iterator.Next() { 72 if f(iterator.Index(), iterator.Value()) { 73 return iterator.Index(), iterator.Value() 74 } 75 } 76 return -1, set.zero 77 }