codesnap.nvim/lua/codesnap/utils/table.lua

81 lines
1.5 KiB
Lua
Raw Permalink Normal View History

2024-02-19 14:27:17 +00:00
local list_utils = require("codesnap.utils.list")
2024-02-13 06:05:36 +00:00
local table_utils = {}
function table_utils.assign(t, props)
for k, v in pairs(props) do
t[k] = v
end
end
function table_utils.merge(t1, t2)
for k, v in pairs(t2) do
t1[k] = v
end
return t1
end
2024-02-19 14:27:17 +00:00
function table_utils.is_array(t)
return type(t[1]) == "number"
end
function table_utils.typeof(value)
if type(value) == "table" then
if table_utils.is_array(value) then
return "array"
else
return "table"
end
end
return type(value)
end
function table_utils.serialize_array(t)
local result = list_utils.map(t, function(ele)
2024-04-27 11:07:41 +00:00
table_utils.to_string(ele)
2024-02-19 14:27:17 +00:00
end)
return "[" .. result.concat(t, ",") .. "]"
end
function table_utils.serialize_table(t)
local result = {}
for key, value in pairs(t) do
2024-04-27 11:07:41 +00:00
table.insert(result, string.format("%s = %s", key, table_utils.to_string(value)))
2024-02-19 14:27:17 +00:00
end
return "{" .. table.concat(result, ",") .. "}"
end
function table_utils.serialize_string(value)
2024-04-27 11:07:41 +00:00
return "[[" .. value .. "]]"
2024-02-19 14:27:17 +00:00
end
2024-04-27 11:07:41 +00:00
function table_utils.to_string(t)
2024-02-19 14:27:17 +00:00
local complex_type_parser = {
array = table_utils.serialize_array,
table = table_utils.serialize_table,
string = table_utils.serialize_string,
}
local parse = complex_type_parser[table_utils.typeof(t)] or function(v)
return v
end
return parse(t)
end
2024-04-27 11:07:41 +00:00
-- function table_utils.to_string(t)
-- local result = ""
--
-- for key, value in pairs(t) do
-- result = result .. key .. ":" .. tostring(value) .. ","
-- end
--
-- return "{" .. result .. "}"
-- end
2024-02-13 06:05:36 +00:00
return table_utils