knucklebones/utils/tables.lua

65 lines
1.4 KiB
Lua
Raw Normal View History

2023-08-12 11:36:14 +02:00
--- Finds the first value in a table that satisfies a condition
---@param table any
---@param cb any @function(v, i) return boolean end
---@return unknown @value or nil
---@return unknown @index or nil
function table.find(table, cb)
for i, v in pairs(table) do
if cb(v) then
return v, i
end
end
return nil, nil
end
function table.filter(table, cb)
local new = {}
for _, v in pairs(table) do
if cb(v) then
table.insert(new, v)
end
end
return new
end
function table.remove_item(list, item)
for i, v in pairs(list) do
if v == item then
table.remove(list, i)
return
end
end
end
---needle can be a value or a function
---@param list table
---@param needle function|number
---@return integer
function table.count(list, needle)
local count = 0
for _, v in pairs(list) do
if type(needle) == "function" and needle(v) or v == needle then
count = count + 1
end
end
return count
end
function table.max(list, cb)
local max = -math.huge
for _, v in pairs(list) do
local value = cb(v)
if value > max then
max = value
end
end
return max
end
function math.randomitem(tbl)
return tbl[math.random(#tbl)]
end
function table.random(tbl)
return tbl[math.random(#tbl)]
end