github.com/m4gshm/gollections@v0.0.13-0.20240331203319-a34a86e58a24/collection/immutable/api.go (about)

     1  // Package immutable provides immutable collection implementations
     2  package immutable
     3  
     4  import (
     5  	"github.com/m4gshm/gollections/c"
     6  	"github.com/m4gshm/gollections/loop"
     7  	"github.com/m4gshm/gollections/map_"
     8  	"github.com/m4gshm/gollections/slice"
     9  )
    10  
    11  // NewSet instantiates set and copies elements to it
    12  func NewSet[T comparable](elements ...T) Set[T] {
    13  	uniques := make(map[T]struct{}, len(elements))
    14  	for _, e := range elements {
    15  		uniques[e] = struct{}{}
    16  	}
    17  	return WrapSet(uniques)
    18  }
    19  
    20  // SetFromLoop creates a set with elements retrieved by the 'next' function.
    21  // The next returns an element with true or zero value with false if there are no more elements.
    22  func SetFromLoop[T comparable](next func() (T, bool)) Set[T] {
    23  	uniques := map[T]struct{}{}
    24  	for e, ok := next(); ok; e, ok = next() {
    25  		uniques[e] = struct{}{}
    26  	}
    27  	return WrapSet(uniques)
    28  }
    29  
    30  // NewMap instantiates an map using key/value pairs
    31  func NewMap[K comparable, V any](elements ...c.KV[K, V]) Map[K, V] {
    32  	return WrapMap(map_.Of(elements...))
    33  }
    34  
    35  // NewMapOf instantiates Map populated by the 'elements' map key/values
    36  func NewMapOf[K comparable, V any](elements map[K]V) Map[K, V] {
    37  	uniques := make(map[K]V, len(elements))
    38  	for key, val := range elements {
    39  		uniques[key] = val
    40  	}
    41  	return WrapMap(uniques)
    42  }
    43  
    44  // MapFromLoop creates a map with elements retrieved converter the 'next' function
    45  func MapFromLoop[K comparable, V any](next func() (K, V, bool)) Map[K, V] {
    46  	uniques := map[K]V{}
    47  	for key, val, ok := next(); ok; key, val, ok = next() {
    48  		uniques[key] = val
    49  	}
    50  	return WrapMap(uniques)
    51  }
    52  
    53  // NewVector instantiates Vector populated by the 'elements' slice
    54  func NewVector[T any](elements ...T) Vector[T] {
    55  	return WrapVector(slice.Clone(elements))
    56  }
    57  
    58  // VectorFromLoop creates a vector with elements retrieved by the 'next' function.
    59  // The next returns an element with true or zero value with false if there are no more elements.
    60  func VectorFromLoop[T any](next func() (T, bool)) Vector[T] {
    61  	return WrapVector(loop.Slice(next))
    62  }