diff --git a/cf-lib/util.lua b/cf-lib/util.lua new file mode 100644 index 0000000..281a96e --- /dev/null +++ b/cf-lib/util.lua @@ -0,0 +1 @@ +require("util/table") \ No newline at end of file diff --git a/cf-lib/util/table.lua b/cf-lib/util/table.lua new file mode 100644 index 0000000..c6a5f13 --- /dev/null +++ b/cf-lib/util/table.lua @@ -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 \ No newline at end of file