Add the merge_dictionaries utility function.
This commit is contained in:
parent
acf0cf26e8
commit
f3ec6022fe
|
@ -0,0 +1,35 @@
|
||||||
|
/// Merge dictionaries together by recursively going through each key. Any
|
||||||
|
/// non-dictionary keys will be overwritten by whichever value comes last.
|
||||||
|
#let merge_dictionaries(
|
||||||
|
/// When two array are found for the same key, merge them together.
|
||||||
|
merge_arrays: true,
|
||||||
|
..args,
|
||||||
|
) = {
|
||||||
|
let output = (:)
|
||||||
|
|
||||||
|
for arg in args.pos() {
|
||||||
|
assert.eq(type(arg), dictionary, message: "Can't merge non-dictionary types.")
|
||||||
|
|
||||||
|
for (key, value) in arg {
|
||||||
|
if key not in output {
|
||||||
|
output.insert(key, value)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
let value_type = type(value)
|
||||||
|
let existing_type = type(output.at(key))
|
||||||
|
|
||||||
|
if value_type == dictionary and existing_type == dictionary {
|
||||||
|
output.at(key) = merge_dictionaries(output.at(key), value)
|
||||||
|
} else if merge_arrays and value_type == array and existing_type == array {
|
||||||
|
for item in value {
|
||||||
|
output.at(key).push(item)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
output.at(key) = value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return output
|
||||||
|
}
|
Loading…
Reference in New Issue