Module:Flag

From Wikimedia Commons, the free media repository
Jump to navigation Jump to search
Lua
CodeDiscussionEditHistoryLinksLink count Subpages:DocumentationTestsResultsSandboxLive code All modules

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

Code

local p = {}

local catFmt = 'Category:Flags with an aspect ratio of %d:%d'
local ratios = {
	-- https://commons.wikimedia.org/wiki/Special:PrefixIndex/Category:Flags_with_an_aspect_ratio_of
	{ 15, 11 },
	{ 18, 11 },
	{ 18, 13 },
	{ 1, 1 },
	{ 1, 2 },
	{ 1, 3 },
	{ 20, 11 },
	{ 21, 16 },
	{ 25, 12 },
	{ 25, 14 },
	{ 2, 1 },
	{ 2, 3 },
	{ 2, 5 },
	{ 3, 2 },
	{ 3, 5 },
	{ 3, 7 },
	{ 3, 8 },
	{ 4, 3 },
	{ 5, 3 },
	{ 7, 4 },
	{ 8, 5 },
	{ 9, 7 },
}

local function getCategoryName(...)
	return string.format(catFmt, ...)
end

local function getSuitableRatios(width, height, threshold)
	local ratio = width / height
	local ret = {}
	for _, ints in pairs(ratios) do
		local diff = math.abs(ratio - (ints[1] / ints[2]))
		if diff < threshold then
			table.insert(ret, { width = ints[1], height = ints[2], diff = diff })
		end
	end
	return ret
end

function p.categories(frame)
	local title = mw.title.new(frame.args[1])
	local file = title.file
	if file == nil then
		return
	end
	local ret = { title.prefixedText .. ' is ' .. file.width .. '×' .. file.height .. 'px' }
	local cat
	local suitableRatios = getSuitableRatios(file.width, file.height, .05)
	for _, tbl in pairs(suitableRatios) do
		table.insert(ret, string.format('Difference with %d:%d is %f', tbl.width, tbl.height, tbl.diff))
		if tbl.diff == 0 then
			cat = getCategoryName(tbl.width, tbl.height)
		end
	end
	if cat then
		table.insert(ret, cat)
	end
	return table.concat(ret, '<br>')
end

return p