Add util/table
This commit is contained in:
parent
b39768cdc5
commit
886b764543
2 changed files with 68 additions and 0 deletions
1
cf-lib/util.lua
Normal file
1
cf-lib/util.lua
Normal file
|
@ -0,0 +1 @@
|
||||||
|
require("util/table")
|
67
cf-lib/util/table.lua
Normal file
67
cf-lib/util/table.lua
Normal file
|
@ -0,0 +1,67 @@
|
||||||
|
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
|
||||||
|
target.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
|
||||||
|
result[k] = v
|
||||||
|
end
|
||||||
|
end
|
||||||
|
return result
|
||||||
|
end
|
Loading…
Add table
Reference in a new issue