github.com/songzhibin97/go-baseutils@v0.0.2-0.20240302024150-487d8ce9c082/structure/sets/linkedhashset/enumerable.go (about)

     1  package linkedhashset
     2  
     3  // Each calls the given function once for each element, passing that element's index and value.
     4  func (set *Set[E]) Each(f func(index int, value E)) {
     5  	iterator := set.Iterator()
     6  	for iterator.Next() {
     7  		f(iterator.Index(), iterator.Value())
     8  	}
     9  }
    10  
    11  // Map invokes the given function once for each element and returns a
    12  // container containing the values returned by the given function.
    13  func (set *Set[E]) Map(f func(index int, value E) E) *Set[E] {
    14  	newSet := New[E]()
    15  	iterator := set.Iterator()
    16  	for iterator.Next() {
    17  		newSet.Add(f(iterator.Index(), iterator.Value()))
    18  	}
    19  	return newSet
    20  }
    21  
    22  // Select returns a new container containing all elements for which the given function returns a true value.
    23  func (set *Set[E]) Select(f func(index int, value E) bool) *Set[E] {
    24  	newSet := New[E]()
    25  	iterator := set.Iterator()
    26  	for iterator.Next() {
    27  		if f(iterator.Index(), iterator.Value()) {
    28  			newSet.Add(iterator.Value())
    29  		}
    30  	}
    31  	return newSet
    32  }
    33  
    34  // Any passes each element of the container to the given function and
    35  // returns true if the function ever returns true for any element.
    36  func (set *Set[E]) Any(f func(index int, value E) bool) bool {
    37  	iterator := set.Iterator()
    38  	for iterator.Next() {
    39  		if f(iterator.Index(), iterator.Value()) {
    40  			return true
    41  		}
    42  	}
    43  	return false
    44  }
    45  
    46  // All passes each element of the container to the given function and
    47  // returns true if the function returns true for all elements.
    48  func (set *Set[E]) All(f func(index int, value E) bool) bool {
    49  	iterator := set.Iterator()
    50  	for iterator.Next() {
    51  		if !f(iterator.Index(), iterator.Value()) {
    52  			return false
    53  		}
    54  	}
    55  	return true
    56  }
    57  
    58  // Find passes each element of the container to the given function and returns
    59  // the first (index,value) for which the function is true or -1,nil otherwise
    60  // if no element matches the criteria.
    61  func (set *Set[E]) Find(f func(index int, value E) bool) (int, E) {
    62  	iterator := set.Iterator()
    63  	for iterator.Next() {
    64  		if f(iterator.Index(), iterator.Value()) {
    65  			return iterator.Index(), iterator.Value()
    66  		}
    67  	}
    68  	return -1, set.zero
    69  }