cf-lib/cf-lib/util/table.lua
2025-02-28 09:39:21 +01:00

95 lines
No EOL
2.6 KiB
Lua

local meld = require("__core__/lualib/meld")
--- Checks if a table contains a certain value.
--- @param table table The table to check
--- @param value any The value to check for
--- @return boolean
function table.contains(table, value)
for _, v in pairs(table) do
if v == value then
return true
end
end
return false
end
--- Assigns all values from source to target without a deep merge.
--- @param target table The table to assign to
--- @param source table The table to assign from
--- @return table The target table
function table.assign(target, source)
for k, v in pairs(source) do
if type(k) == "number" then
if (v ~= nil) then
table.insert(target, v)
end
else
target[k] = v
end
end
return target
end
--- Deeply merges two tables together, with the source table overwriting the target table.
--- @param target table The table to merge into
--- @param source table The table to merge from
--- @return table The target table
function table.merge(target, source)
meld(target, source)
return target
end
--- Removes a value from a table.
--- @param target table The table to remove from
--- @param value any The value to remove
--- @return table The target table
table.removeValue = function(target, value)
for i, v in ipairs(target) do
if v == value then
table.remove(target, i)
return target
end
end
end
--- Filters a table based on a predicate function.
--- When the predicate returns true, the value is kept in the table.
--- @param target table The table to filter
--- @param predicate fun(value: any, key: any): boolean The predicate function
function table.filter(target, predicate)
local result = {}
for k, v in pairs(target) do
if predicate(v, k) then
if type(k) == "number" then
table.insert(result, v)
else
result[k] = v
end
end
end
return result
end
--- Concatenates two tables into a new table.
--- @param table1 table The first table
--- @param table2 table The second table
--- @return table The concatenated table
function table.concat(table1, table2)
local result = {}
for _, v in pairs(table1) do
table.insert(result, v)
end
for _, v in pairs(table2) do
table.insert(result, v)
end
return result
end
--- Trims nil values from a table.
--- @param target table The table to trim
--- @return table The trimmed table
function table.trim(target)
return table.filter(target, function(v)
return v ~= nil
end)
end