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