Difference between revisions of "Module:SortUtil"

From Leaguepedia | League of Legends Esports Wiki
Jump to: navigation, search
[checked revision][checked revision]
((via Mediawiker ST3))
((via Mediawiker ST3))
Line 7: Line 7:
 
local thisKey = keyTbl[i]
 
local thisKey = keyTbl[i]
 
if a[thisKey] == b[thisKey] then
 
if a[thisKey] == b[thisKey] then
return h.compareTwoArraysByKey(a, b, keyTbl, i+1)
+
return h.compareTwoArraysByKeys(a, b, keyTbl, i+1)
 
end
 
end
 
if tonumber(a[thisKey]) and tonumber(b[thisKey]) then
 
if tonumber(a[thisKey]) and tonumber(b[thisKey]) then

Revision as of 12:42, 16 May 2019

To edit the documentation or categories for this module, click here.


local util_args = require('Module:ArgsUtil')
local util_table = require('Module:TableUtil')

local h = {}
function h.compareTwoArraysByKeys(a, b, keyTbl, i)
	if not i == #keyTbl then return nil end
	local thisKey = keyTbl[i]
	if a[thisKey] == b[thisKey] then
		return h.compareTwoArraysByKeys(a, b, keyTbl, i+1)
	end
	if tonumber(a[thisKey]) and tonumber(b[thisKey]) then
		return tonumber(a[thisKey]) > tonumber(b[thisKey])
	else
		return a[thisKey] > b[thisKey]
	end
end

local p = {}

function p.sortListOfTablesByKeys(tbl, key, increasing)
	local keyTbl = util_table.guaranteeTable(key)
	table.sort(tbl, function(a,b)
		if increasing then
			return h.compareTwoArraysByKeys(a, b, keyTbl, 1)
		else
			return h.compareTwoArraysByKeys(b, a, keyTbl, 1)
		end
	end)
end

function p.sortOrderedDictByKeys(tbl, key, increasing)
	local keyTbl = util_table.guaranteeTable(key)
	table.sort(tbl, function(a,b)
		if increasing then
			local result = h.compareTwoArraysByKeys(tbl[a], tbl[b], keyTbl, 1)
			if result == nil then
				return a > b
			end
		else
			local result = h.compareTwoArraysByKeys(tbl[b], tbl[a], keyTbl, 1)
			if result == nil then
				return a < b
			end
		end
	end)
end

return p