(Tiny library for sorting data) |
(Filter function) |
||
(One intermediate revision by the same user not shown) | |||
Line 29: | Line 29: | ||
return sorted | return sorted | ||
end | |||
p.filter = function(data, predicate) | |||
local filtered = {} | |||
for i,v in ipairs(data) do | |||
if predicate(v) then | |||
table.insert(filtered, v) | |||
end | |||
end | |||
for k,v in pairs(data) do | |||
if type(k) ~= 'number' and predicate(v) then | |||
filtered[k] = v | |||
end | |||
end | |||
return filtered | |||
end | end | ||
Line 39: | Line 54: | ||
return false | return false | ||
end | end | ||
-- Can't compare booleans in lua | |||
if a == false then | |||
return b | |||
end | |||
if a == true then | |||
return false | |||
end | |||
return a < b | return a < b | ||
end | end |
Latest revision as of 03:35, 8 March 2023
Documentation for this module may be created at Module:Data/doc
p = {} p.keys = function(data) local keys = {} for k,v in pairs(data) do table.insert(keys, k) end return keys end p.sort = function(data, comparison) if isTable(comparison) then comparison = p.combineComparisons(comparison) end local keyOrder = p.keys(data) function cmp(key1, key2) return comparison(data[key1], data[key2]) end table.sort(keyOrder, cmp) local sorted = {} for i,k in ipairs(keyOrder) do table.insert(sorted, data[k]) end return sorted end p.filter = function(data, predicate) local filtered = {} for i,v in ipairs(data) do if predicate(v) then table.insert(filtered, v) end end for k,v in pairs(data) do if type(k) ~= 'number' and predicate(v) then filtered[k] = v end end return filtered end safeCompare = function(a, b) if type(a) ~= type(b) then return type(a) < type(b) end if a == nil then return false end -- Can't compare booleans in lua if a == false then return b end if a == true then return false end return a < b end p.asc = safeCompare p.desc = function(a, b) return p.asc(b, a) end p.on = function(f, c) return function(a, b) return c(f(a), f(b)) end end p.combineComparisons = function(comparisons) return function(a, b) for i,c in ipairs(comparisons) do if c(a, b) then return true end if c(b, a) then return false end end return false end end function isTable(t) return type(t) == 'table' end safeGet = function(data, key) if isTable(data) then return data[key] end end p.path = function(path) return function(data) local result = data for i,k in ipairs(path) do result = safeGet(result, k) end return result end end return p