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