github.com/m4gshm/gollections@v0.0.13-0.20240331203319-a34a86e58a24/collection/mutable/ordered/api.go (about) 1 // Package ordered provides mutable 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]int, l) 14 order = make([]T, 0, l) 15 ) 16 pos := 0 17 for _, e := range elements { 18 order, pos = addToSet(e, uniques, order, pos) 19 } 20 return WrapSet(order, uniques) 21 } 22 23 // NewSetCap creates a set with a predefined capacity 24 func NewSetCap[T comparable](capacity int) *Set[T] { 25 return WrapSet(make([]T, 0, capacity), make(map[T]int, capacity)) 26 } 27 28 // SetFromLoop creates a set with elements retrieved by the 'next' function. 29 // The next returns an element with true or zero value with false if there are no more elements. 30 func SetFromLoop[T comparable](next func() (T, bool)) *Set[T] { 31 var ( 32 uniques = map[T]int{} 33 order []T 34 pos = 0 35 ) 36 for e, ok := next(); ok; e, ok = next() { 37 order, pos = addToSet(e, uniques, order, pos) 38 } 39 return WrapSet(order, uniques) 40 } 41 42 // NewMap instantiates a map using key/value pairs 43 func NewMap[K comparable, V any](elements ...c.KV[K, V]) *Map[K, V] { 44 var ( 45 l = len(elements) 46 uniques = make(map[K]V, l) 47 order = make([]K, 0, l) 48 ) 49 for _, kv := range elements { 50 order = addToMap(kv.Key(), kv.Value(), order, uniques) 51 } 52 return WrapMap(order, uniques) 53 } 54 55 // NewMapCap instantiates Map with a predefined capacity 56 func NewMapCap[K comparable, V any](capacity int) *Map[K, V] { 57 return WrapMap(make([]K, capacity), make(map[K]V, capacity)) 58 } 59 60 // NewMapOf instantiates Map populated by the 'elements' map key/values 61 func NewMapOf[K comparable, V any](order []K, elements map[K]V) *Map[K, V] { 62 uniques := make(map[K]V, len(elements)) 63 for _, key := range order { 64 uniques[key] = elements[key] 65 } 66 return WrapMap(clone.Of(order), uniques) 67 } 68 69 // MapFromLoop creates a map with elements retrieved converter the 'next' function 70 func MapFromLoop[K comparable, V any](next func() (K, V, bool)) *Map[K, V] { 71 var ( 72 uniques = map[K]V{} 73 order = []K{} 74 ) 75 for key, val, ok := next(); ok; key, val, ok = next() { 76 order = addToMap(key, val, order, uniques) 77 } 78 return WrapMap(order, uniques) 79 }