github.com/m4gshm/gollections@v0.0.13-0.20240331203319-a34a86e58a24/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  // Next returns the next element if it exists
    27  func (i *SetIter[K]) Next() (key K, ok bool) {
    28  	if i != nil {
    29  		key, _, ok = i.Iter.Next()
    30  		i.currentKey = key
    31  		i.ok = ok
    32  	}
    33  	return key, ok
    34  }
    35  
    36  // Delete deletes the current element
    37  func (i *SetIter[K]) Delete() {
    38  	if i != nil && i.ok {
    39  		i.del(i.currentKey)
    40  	}
    41  }