github.com/m4gshm/gollections@v0.0.13-0.20240331203319-a34a86e58a24/collection/mutable/ordered/set_iter.go (about)

     1  package ordered
     2  
     3  import (
     4  	"github.com/m4gshm/gollections/c"
     5  	"github.com/m4gshm/gollections/loop"
     6  	"github.com/m4gshm/gollections/slice"
     7  )
     8  
     9  // NewSetIter creates a set's iterator.
    10  func NewSetIter[T any](elements *[]T, del func(v T)) SetIter[T] {
    11  	return SetIter[T]{elements: elements, current: slice.IterNoStarted, del: del}
    12  }
    13  
    14  // SetIter set iterator
    15  type SetIter[T any] struct {
    16  	elements *[]T
    17  	current  int
    18  	del      func(v T)
    19  }
    20  
    21  var (
    22  	_ c.Iterator[any]    = (*SetIter[any])(nil)
    23  	_ c.DelIterator[any] = (*SetIter[any])(nil)
    24  )
    25  
    26  // All is used to iterate through the collection using `for ... range`. Supported since go 1.22 with GOEXPERIMENT=rangefunc enabled.
    27  func (i *SetIter[T]) All(consumer func(element T) bool) {
    28  	loop.All(i.Next, consumer)
    29  }
    30  
    31  // For takes elements retrieved by the iterator. Can be interrupt by returning Break
    32  func (i *SetIter[T]) For(consumer func(element T) error) error {
    33  	return loop.For(i.Next, consumer)
    34  }
    35  
    36  // ForEach takes all elements retrieved by the iterator.
    37  func (i *SetIter[T]) ForEach(consumer func(element T)) {
    38  	loop.ForEach(i.Next, consumer)
    39  }
    40  
    41  // Next returns the next element.
    42  // The ok result indicates whether the element was returned by the iterator.
    43  // If ok == false, then the iteration must be completed.
    44  func (i *SetIter[T]) Next() (t T, ok bool) {
    45  	if !(i == nil || i.elements == nil) {
    46  		if slice.HasNext(*i.elements, i.current) {
    47  			i.current++
    48  			return slice.Gett(*i.elements, i.current)
    49  		}
    50  	}
    51  	return t, ok
    52  }
    53  
    54  // Size returns the iterator capacity
    55  func (i *SetIter[T]) Size() (capacity int) {
    56  	if !(i == nil || i.elements == nil) {
    57  		capacity = len(*i.elements)
    58  	}
    59  	return capacity
    60  }
    61  
    62  // Delete deletes the current element
    63  func (i *SetIter[T]) Delete() {
    64  	if !(i == nil || i.elements == nil) {
    65  		if v, ok := slice.Gett(*i.elements, i.current); ok {
    66  			i.current--
    67  			i.del(v)
    68  		}
    69  	}
    70  }