Anonymous

Module:FunList: Difference between revisions

From Melvor Idle
no edit summary
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.sortData = {}
self.sortSelectors = {}
return self
return self
end
end
Line 28: Line 28:
return false, nil
return false, nil
end
function funlist:finishSort()
local sortFunc = function(left, right)
for _, sortSelector in pairs(self.sortData) do
local leftVal = sortSelector(left)
local rightVal = sortSelector(right)
if leftVal ~= rightVal then
return leftVal < rightVal
end
end
end
table.sort(self.mytable, sortFunc)
self.sortData = {}
return self.mytable
end
function funlist:sortByTest(selector)
assert(selector)
table.insert(self.sortData, selector)
return self
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:sortBy(selector)
function funlist:executeSort()
assert(selector)
local sortFunc = function(left, right)
local sortFunc = function(left, right)
return selector(left) < selector(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)
local sortFunc = function(left, right)
table.insert(self.sortData, {
return selector(left) > selector(right)
selector = selector,
end
ascending = false
table.sort(self.mytable, sortFunc)
})
return self
return self
end
 
function funlist:thenBy(selector)
return self:sortBy(selector)
end
 
function funlist:thenByDecending(selector)
return self:sortByDecending(selector)
end
end


2,875

edits