aboutsummaryrefslogtreecommitdiff
path: root/immutable.go
diff options
context:
space:
mode:
Diffstat (limited to 'immutable.go')
-rw-r--r--immutable.go49
1 files changed, 49 insertions, 0 deletions
diff --git a/immutable.go b/immutable.go
index eefc573..b3d7dcb 100644
--- a/immutable.go
+++ b/immutable.go
@@ -707,6 +707,20 @@ func NewMap[K comparable, V any](hasher Hasher[K]) *Map[K, V] {
}
}
+// NewMapOf returns a new instance of Map, containing a map of provided entries.
+//
+// If hasher is nil, a default hasher implementation will automatically be chosen based on the first key added.
+// Default hasher implementations only exist for int, string, and byte slice types.
+func NewMapOf[K comparable, V any](hasher Hasher[K], entries map[K]V) *Map[K, V] {
+ m := &Map[K, V]{
+ hasher: hasher,
+ }
+ for k, v := range entries {
+ m.set(k, v, true)
+ }
+ return m
+}
+
// Len returns the number of elements in the map.
func (m *Map[K, V]) Len() int {
return m.size
@@ -738,6 +752,18 @@ func (m *Map[K, V]) Set(key K, value V) *Map[K, V] {
return m.set(key, value, false)
}
+// SetMany returns a map with the keys set to the new values. nil values are allowed.
+//
+// This function will return a new map even if the updated value is the same as
+// the existing value because Map does not track value equality.
+func (m *Map[K, V]) SetMany(entries map[K]V) *Map[K, V] {
+ n := m.clone()
+ for k, v := range entries {
+ n.set(k, v, true)
+ }
+ return n
+}
+
func (m *Map[K, V]) set(key K, value V, mutable bool) *Map[K, V] {
// Set a hasher on the first value if one does not already exist.
hasher := m.hasher
@@ -1582,6 +1608,20 @@ func NewSortedMap[K comparable, V any](comparer Comparer[K]) *SortedMap[K, V] {
}
}
+// NewSortedMapOf returns a new instance of SortedMap, containing a map of provided entries.
+//
+// If comparer is nil then a default comparer is set after the first key is inserted. Default comparers
+// exist for int, string, and byte slice keys.
+func NewSortedMapOf[K comparable, V any](comparer Comparer[K], entries map[K]V) *SortedMap[K, V] {
+ m := &SortedMap[K, V]{
+ comparer: comparer,
+ }
+ for k, v := range entries {
+ m.set(k, v, true)
+ }
+ return m
+}
+
// Len returns the number of elements in the sorted map.
func (m *SortedMap[K, V]) Len() int {
return m.size
@@ -1602,6 +1642,15 @@ func (m *SortedMap[K, V]) Set(key K, value V) *SortedMap[K, V] {
return m.set(key, value, false)
}
+// SetMany returns a map with the keys set to the new values.
+func (m *SortedMap[K, V]) SetMany(entries map[K]V) *SortedMap[K, V] {
+ n := m.clone()
+ for k, v := range entries {
+ n.set(k, v, true)
+ }
+ return n
+}
+
func (m *SortedMap[K, V]) set(key K, value V, mutable bool) *SortedMap[K, V] {
// Set a comparer on the first value if one does not already exist.
comparer := m.comparer