2,875
edits
No edit summary |
No edit summary |
||
Line 9: | Line 9: | ||
local self = setmetatable({}, funlist) | local self = setmetatable({}, funlist) | ||
self.mytable = tbl | self.mytable = tbl | ||
self. | self.sortSelectors = {} | ||
return self | return self | ||
end | end | ||
Line 28: | Line 28: | ||
return false, nil | return false, nil | ||
end | end | ||
Line 217: | Line 195: | ||
end | end | ||
-- Sorts the internal table by default Lua sorting behaviour | |||
-- Unless specific sorting is requested. | |||
function funlist:sort() | function funlist:sort() | ||
table.sort(self.mytable) | function hasSortData() | ||
for _, _ in pairs(self.sortSelectors) do | |||
return true | |||
end | |||
end | |||
if hasSortData() == true then | |||
self:executeSort() | |||
else | |||
table.sort(self.mytable) | |||
end | |||
return self | return self | ||
end | end | ||
Line 227: | Line 217: | ||
end | end | ||
function funlist: | function funlist:executeSort() | ||
local sortFunc = function(left, right) | local sortFunc = function(left, right) | ||
for _, sortMeta in pairs(self.sortSelectors) do | |||
local selector = sort.selector | |||
local sortAscending = sort.ascending | |||
local leftVal = sortSelector(left) | |||
local rightVal = sortSelector(right) | |||
if leftVal ~= rightVal then | |||
if sortAscending then | |||
return leftVal < rightVal | |||
else | |||
return leftVal > rightVal | |||
end | |||
end | |||
end | |||
end | end | ||
table.sort(self.mytable, sortFunc) | table.sort(self.mytable, sortFunc) | ||
self.sortSelectors = {} | |||
return self | |||
end | |||
-- Adds a sort condition | |||
function funlist:sortBy(selector) | |||
assert(selector) | |||
table.insert(self.sortData, { | |||
selector = selector, | |||
ascending = true | |||
}) | |||
return self | return self | ||
end | end | ||
Line 238: | Line 252: | ||
function funlist:sortByDecending(selector) | function funlist:sortByDecending(selector) | ||
assert(selector) | assert(selector) | ||
table.insert(self.sortData, { | |||
selector = selector, | |||
ascending = false | |||
}) | |||
return self | return self | ||
end | |||
function funlist:thenBy(selector) | |||
return self:sortBy(selector) | |||
end | |||
function funlist:thenByDecending(selector) | |||
return self:sortByDecending(selector) | |||
end | end | ||
edits