Nikita Kruglickiy 09be0ea795 UPDATE
2023-05-22 19:06:26 +03:00

112 lines
2.2 KiB
Lua

-- @name koptilnya/libs/table
function table.chunk(tbl, size)
size = size or 1
size = size > 0 and size or 1
local result = {}
local tblKeys = table.getKeys(tbl)
for k, v in pairs(tblKeys) do
local chunkId = math.ceil(k / size)
if not result[chunkId] then
result[chunkId] = {}
end
result[chunkId][v] = tbl[v]
end
return result
end
function table.deepcopy(orig)
local orig_type = type(orig)
local copy
if orig_type == 'table' then
copy = {}
for orig_key, orig_value in next, orig, nil do
copy[table.deepcopy(orig_key)] = table.deepcopy(orig_value)
end
setmetatable(copy, table.deepcopy(getmetatable(orig)))
else -- number, string, boolean, etc
copy = orig
end
return copy
end
function table.contains(tbl, ...)
local argCount = #arg
if argCount == 1 then
return table.hasValue(tbl, arg[1])
elseif argCount > 1 then
local result = true
for _, v in pairs(arg) do
if not table.hasValue(tbl, v) then
result = true
break
end
end
return result
end
end
function table.map(tbl, action)
local res = {}
for idx, field in ipairs(tbl) do
table.insert(res, action(field, idx))
end
return res
end
function table.filter(tbl, filterFunc)
local res = {}
for idx, field in ipairs(tbl) do
if filterFunc(field, idx) == true then
table.insert(res, field)
end
end
return res
end
function table.find(tbl, predicate)
for _, field in ipairs(tbl) do
if predicate(field) == true then
return field
end
end
return nil
end
function table.reduce(tbl, reducer, init)
local accum = init
for idx, field in ipairs(tbl) do
accum = reducer(accum, field, idx)
end
return accum
end
function table.every(tbl, predicate)
for i, field in pairs(tbl) do
if not predicate(field, i) then
return false
end
end
return true
end
function table.some(tbl, predicate)
return table.find(tbl, predicate) ~= nil
end