We're currently performing an overhaul of our entire tournament results system so results will be missing from team and player pages for a while, and there may be some errors on tournament pages. Please bear with us as we complete this update.

Module:SortUtil

From Call of Duty Esports Wiki
Jump to: navigation, search

Documentation for this module may be created at Module:SortUtil/doc

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

local lang = mw.getLanguage('en')

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

function h.compareNumberOrString(a, b, increasing)
	if increasing then return h.compareNumberOrString(b, a, false) end
	if tonumber(a) and tonumber(b) then
		return tonumber(a) > tonumber(b)
	end
	return lang:caseFold(a) > lang:caseFold(b)
end

local p = {}

function p.tablesByKeys(tbl, key, increasing)
	local keyTbl = util_table.guaranteeTable(key)
	local incTbl = util_table.guaranteeTable(increasing) or {}
	table.sort(tbl,
		function(a,b)
			return h.compareTwoArraysByKeys(a, b, keyTbl, incTbl, 1)
		end)
end

function p.dictByKeys(tbl, key, increasing)
	local keyTbl = util_table.guaranteeTable(key)
	local incTbl = util_table.guaranteeTable(increasing) or {}
	table.sort(tbl,
		function(a,b)
			local result = h.compareTwoArraysByKeys(tbl[a], tbl[b], keyTbl, incTbl, 1)
			if result == nil then
				return a < b
			end
			return result
		end)
end

function p.sortConstantDictionary(tbl)
	table.sort(tbl,
		function(a,b)
			return h.compareNumberOrString(tbl[a], tbl[b])
		end)
end

return p