Skip to content

Commit

Permalink
maps: add maps.merge_by_replace_to/2 and maps.merge_by_replace/2 gene…
Browse files Browse the repository at this point in the history
…ric utility functions
  • Loading branch information
spytheman committed Nov 5, 2023
1 parent 9ec8807 commit f47cc8c
Show file tree
Hide file tree
Showing 2 changed files with 110 additions and 0 deletions.
22 changes: 22 additions & 0 deletions vlib/maps/maps.v
Original file line number Diff line number Diff line change
Expand Up @@ -68,3 +68,25 @@ pub fn from_array[T](array []T) map[int]T {

return mp
}

// merge_by_replace_to adds all the elements of `m2` to the mutable map `m1`.
// If a key exists in both maps, the value from `m1` will be overwritten by the
// value from `m2`.
// Note that this function modifes `m1`, while `m2` will not be.
pub fn merge_by_replace_to[K, V](mut m1 map[K]V, m2 map[K]V) {
for k, v in m2 {
m1[k] = v
}
}

// merge_by_replace produces a map, that is the result of merging
// the first map m1 with the second map `m2`. If a key exists in both maps,
// the value from m2, will overwrite the value from m1.
// The original maps will not be modified. The return value is a new map.
pub fn merge_by_replace[K, V](m1 map[K]V, m2 map[K]V) map[K]V {
mut res := m1.clone()
for k, v in m2 {
res[k] = v
}
return res
}
88 changes: 88 additions & 0 deletions vlib/maps/maps_test.v
Original file line number Diff line number Diff line change
Expand Up @@ -107,3 +107,91 @@ fn test_from_array() {
5: 'f'
}
}

fn test_merge_by_replace_to() {
mut m1 := {
'abc': 'def'
'aa': 'bb'
}
m2 := {
'xyz': 'zyx'
'aa': 'dd'
}
merge_by_replace_to(mut m1, m2)
assert m1 == {
'abc': 'def'
'aa': 'dd'
'xyz': 'zyx'
}
assert m2 == {
'xyz': 'zyx'
'aa': 'dd'
}
//
mut im1 := {
11: 22
33: 44
}
im2 := {
55: 66
33: 999
}
merge_by_replace_to(mut im1, im2)
assert im1 == {
11: 22
33: 999
55: 66
}
assert im2 == {
55: 66
33: 999
}
}

fn test_merge_by_replace() {
m1 := {
'abc': 'def'
'aa': 'bb'
}
m2 := {
'xyz': 'zyx'
'aa': 'dd'
}
res := merge_by_replace(m1, m2)
assert res == {
'abc': 'def'
'aa': 'dd'
'xyz': 'zyx'
}
assert m1 == {
'abc': 'def'
'aa': 'bb'
}
assert m2 == {
'xyz': 'zyx'
'aa': 'dd'
}
//
mut im1 := {
11: 22
33: 44
}
im2 := {
55: 66
33: 999
}
ires := merge_by_replace(im1, im2)
assert im1 == {
11: 22
33: 44
}
assert im2 == {
55: 66
33: 999
}
assert ires == {
11: 22
33: 999
55: 66
}
}

0 comments on commit f47cc8c

Please sign in to comment.