(Tiny library for sorting data) |
(Comparison for booleans) |
||
| Line 39: | Line 39: | ||
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 | ||
Revision as of 20:57, 7 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
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