github.com/m4gshm/gollections@v0.0.10/collection/mutable/set_iter.go (about)

     1  package mutable
     2  
     3  import (
     4  	"github.com/m4gshm/gollections/c"
     5  	"github.com/m4gshm/gollections/map_"
     6  )
     7  
     8  // NewSetIter creates SetIter instance.
     9  func NewSetIter[K comparable](uniques map[K]struct{}, del func(element K)) SetIter[K] {
    10  	return SetIter[K]{KeyIter: map_.NewKeyIter(uniques), del: del}
    11  }
    12  
    13  // SetIter is the Set Iterator implementation.
    14  type SetIter[K comparable] struct {
    15  	map_.KeyIter[K, struct{}]
    16  	del        func(element K)
    17  	currentKey K
    18  	ok         bool
    19  }
    20  
    21  var (
    22  	_ c.Iterator[int]    = (*SetIter[int])(nil)
    23  	_ c.DelIterator[int] = (*SetIter[int])(nil)
    24  )
    25  
    26  var _ c.IterFor[int, *SetIter[int]] = (*SetIter[int])(nil)
    27  
    28  // Next returns the next element if it exists
    29  func (i *SetIter[K]) Next() (key K, ok bool) {
    30  	if i != nil {
    31  		key, _, ok = i.Iter.Next()
    32  		i.currentKey = key
    33  		i.ok = ok
    34  	}
    35  	return key, ok
    36  }
    37  
    38  // Delete deletes the current element
    39  func (i *SetIter[K]) Delete() {
    40  	if i != nil && i.ok {
    41  		i.del(i.currentKey)
    42  	}
    43  }
    44  
    45  // Start is used with for loop construct like 'for i, val, ok := i.Start(); ok; val, ok = i.Next() { }'
    46  func (i *SetIter[K]) Start() (*SetIter[K], K, bool) {
    47  	n, ok := i.Next()
    48  	return i, n, ok
    49  }