v / vlib / maps / maps.v
119 lines · 99 sloc · 2.37 KB · 0dd4e8c55d502f8f1d1131ed4c477d904a81ad76
Raw
1module maps
2
3// filter filters map entries by the given predicate function
4pub fn filter[K, V](m map[K]V, f fn (key K, val V) bool) map[K]V {
5 mut mp := map[K]V{}
6
7 for k, v in m {
8 $if V is $interface {
9 if f(k, unsafe { v }) {
10 mp[k] = v
11 }
12 } $else {
13 if f(k, v) {
14 mp[k] = v
15 }
16 }
17 }
18
19 return mp
20}
21
22// to_array maps map entries into one-dimensional array
23pub fn to_array[K, V, I](m map[K]V, f fn (key K, val V) I) []I {
24 mut a := []I{cap: m.len}
25
26 for k, v in m {
27 $if V is $interface {
28 a << f(k, unsafe { v })
29 } $else {
30 a << f(k, v)
31 }
32 }
33
34 return a
35}
36
37// flat_map maps map entries into arrays and flattens into a one-dimensional array
38pub fn flat_map[K, V, I](m map[K]V, f fn (key K, val V) []I) []I {
39 mut a := []I{cap: m.len}
40
41 for k, v in m {
42 $if V is $interface {
43 a << f(k, unsafe { v })
44 } $else {
45 a << f(k, v)
46 }
47 }
48
49 return a
50}
51
52// to_map maps map entries into new entries and constructs a new map
53pub fn to_map[K, V, X, Y](m map[K]V, f fn (key K, val V) (X, Y)) map[X]Y {
54 mut mp := map[X]Y{}
55
56 for k, v in m {
57 $if V is $interface {
58 x, y := f(k, unsafe { v })
59 mp[x] = y
60 } $else {
61 x, y := f(k, v)
62 mp[x] = y
63 }
64 }
65
66 return mp
67}
68
69// invert returns a new map, created by swapping key to value and vice versa for each entry.
70pub fn invert[K, V](m map[K]V) map[V]K {
71 mut mp := map[V]K{}
72
73 for k, v in m {
74 mp[v] = k
75 }
76
77 return mp
78}
79
80// from_array maps array into map with index to element per entry
81pub fn from_array[T](array []T) map[int]T {
82 mut mp := map[int]T{}
83
84 for i, e in array {
85 mp[i] = e
86 }
87
88 return mp
89}
90
91// merge_in_place merges all elements of `m2` into the mutable map `m1`.
92// If a key exists in both maps, the value from `m1` will be overwritten by the
93// value from `m2`.
94// Note that this function modifes `m1`, while `m2` will not be.
95pub fn merge_in_place[K, V](mut m1 map[K]V, m2 map[K]V) {
96 for k, v in m2 {
97 $if v is $map {
98 m1[k] = v.clone()
99 } $else {
100 m1[k] = v
101 }
102 }
103}
104
105// merge produces a map, that is the result of merging the first map `m1`,
106// with the second map `m2`. If a key exists in both maps, the value from m2,
107// will override the value from m1.
108// The original maps `m1` and `m2`, will not be modified. The return value is a new map.
109pub fn merge[K, V](m1 map[K]V, m2 map[K]V) map[K]V {
110 mut res := m1.clone()
111 for k, v in m2 {
112 $if v is $map {
113 res[k] = v.clone()
114 } $else {
115 res[k] = v
116 }
117 }
118 return res
119}
120