-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmap_join.go
More file actions
62 lines (58 loc) · 1.66 KB
/
Copy pathmap_join.go
File metadata and controls
62 lines (58 loc) · 1.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package gofu
import "maps"
// Merge returns a new map containing entries from m merged with all others. [ Immutable ] [ time: O(n+m); space: O(n+m)]
// For duplicate keys, values from later maps overwrite earlier ones.
//
// Example:
//
// a := gofu.Map[string, int]{"a": 1, "b": 2}
// b := gofu.Map[string, int]{"b": 3, "c": 4}
// a.Merge(b) // Map[string, int]{"a": 1, "b": 3, "c": 4}
func (m Map[K, V]) Merge(others ...Map[K, V]) Map[K, V] {
total := len(m)
for _, other := range others {
total += len(other)
}
result := make(Map[K, V], total)
maps.Copy(result, m)
for _, other := range others {
maps.Copy(result, other)
}
return result
}
// Intersect returns a new map with keys present in both maps. [ Immutable ] [ time: O(n+m); space: O(min(n,m)) ]
//
// Values from m are kept.
//
// Example:
//
// a := gofu.Map[string, int]{"a": 1, "b": 2, "c": 3}
// b := gofu.Map[string, int]{"b": 20, "c": 30, "d": 40}
// a.Intersect(b) // Map[string, int]{"b": 2, "c": 3}
func (m Map[K, V]) Intersect(other Map[K, V]) Map[K, V] {
left, right := m, other
if len(m) > len(other) {
left, right = other, m
}
result := make(Map[K, V], len(left))
for k := range left {
if _, ok := right[k]; ok {
result[k] = m[k]
}
}
return result
}
// Difference returns a new map with keys from m that are not present in other. [ Immutable ] [ time: O(n+m); space: O(n)]
//
// Example:
//
// a := gofu.Map[string, int]{"a": 1, "b": 2, "c": 3}
// b := gofu.Map[string, int]{"b": 20, "d": 40}
// a.Difference(b) // Map[string, int]{"a": 1, "c": 3}
func (m Map[K, V]) Difference(other Map[K, V]) Map[K, V] {
result := maps.Clone(m)
for k := range other {
delete(result, k)
}
return result
}