feat(util): better deep merging with `Util.merge`

This commit is contained in:
Folke Lemaitre 2023-01-08 14:58:17 +01:00
parent b178daf9dc
commit 6a31b97e37
No known key found for this signature in database
GPG Key ID: 41F8B1FBACAE2040
1 changed files with 27 additions and 0 deletions

View File

@ -286,4 +286,31 @@ function M.debug(msg, level, opts)
end
end
local function can_merge(v)
return type(v) == "table" and (vim.tbl_isempty(v) or not M.is_list(v))
end
--- Merges the values similar to vim.tbl_deep_extend with the **force** behavior,
--- but the values can be any type, in which case they override the values on the left.
--- Values will me merged in-place in the first left-most table. If you want the result to be in
--- a new table, then simply pass an empty table as the first argument `vim.merge({}, ...)`
--- Supports clearing values by setting a key to `vim.NIL`
function M.merge(...)
local values = { ... }
local ret = values[1]
for i = 2, #values, 1 do
local value = values[i]
if can_merge(ret) and can_merge(value) then
for k, v in pairs(value) do
ret[k] = M.merge(ret[k], v)
end
elseif value == vim.NIL then
ret = nil
else
ret = value
end
end
return ret
end
return M