opus/sys/modules/opus/map.lua

53 lines
913 B
Lua
Raw Normal View History

2019-02-25 14:02:40 +00:00
-- convience functions for tables with key/value pairs
local Util = require('opus.util')
2019-02-25 14:02:40 +00:00
local Map = { }
2019-02-26 13:17:53 +00:00
-- TODO: refactor
Map.merge = Util.merge
Map.shallowCopy = Util.shallowCopy
2019-05-12 14:02:46 +00:00
Map.find = Util.find
Map.filter = Util.filter
Map.transpose = Util.transpose
2019-02-26 13:17:53 +00:00
2019-02-25 14:02:40 +00:00
function Map.removeMatches(t, values)
local function matchAll(entry)
for k, v in pairs(values) do
if entry[k] ~= v then
return
end
end
return true
end
2019-06-18 19:19:24 +00:00
for _, key in pairs(Util.keys(t)) do
if matchAll(t[key]) then
t[key] = nil
2019-02-25 14:02:40 +00:00
end
end
end
-- remove table entries if passed function returns false
function Map.prune(t, fn)
for _,k in pairs(Util.keys(t)) do
local v = t[k]
if type(v) == 'table' then
2019-02-26 13:17:53 +00:00
t[k] = Map.prune(v, fn)
2019-02-25 14:02:40 +00:00
end
if not fn(t[k]) then
t[k] = nil
end
end
return t
end
2019-02-26 13:17:53 +00:00
function Map.size(list)
local length = 0
for _ in pairs(list) do
length = length + 1
end
return length
end
2019-02-25 14:02:40 +00:00
return Map