Jump to content

Module:Political party/sandbox

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Gonnym (talk | contribs) at 09:50, 10 September 2021. The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
local p = {}

local categories = {
	party_not_in_list = "[[Category:Pages using Political names with unknown party]]",
}

local function shallowCopy(t)
	local t2 = {}
	for k, v in pairs(t) do
		t2[k] = v
	end
	return t2
end

local function getFirstLetter(party)
	local index = mw.ustring.sub(party, 1, 1)
	-- Set index for non-A-Z starts
	if string.match(index, '%A') then
		index = '1'
	end
	return index
end

local function getPartyData(party)
	local index = getFirstLetter(party)
	-- Load data from submodule
	local data = mw.loadData('Module:Political names/' .. index)
	local data_all = data.full
	local party_alt = data.alternate[party]
	local party_data = {}

	-- Check if the party is listed in the alternate list.
	if party_alt then
		local party_name = party_alt.main

		-- Check if the main entry is in the same letter module.
		if data_all[party_name] then
			party = data_all[party_name]
		else
			-- Get new letter module.
			index = getFirstLetter(party_name)
			data = mw.loadData('Module:Political names/' .. index)
			party = data.full[party_name]
		end
		party_data = shallowCopy(party)
		-- Override values
		party_data.abbrev = party_alt.abbrev or party.abbrev
		party_data.shortname = party_alt.shortname or party.shortname
	else
		party = data_all[party]
		party_data = shallowCopy(party)
	end
	return party_data
end

local function stripToNil(text)
	-- If text is a string, return its trimmed content, or nil if empty.
	-- Otherwise return text (which may, for example, be nil).
	if type(text) == 'string' then
		text = text:match('(%S.-)%s*$')
	end
	return text
end

-- Example of having all the data - color and names - in one table. Requires one page to be edited instead of two when adding a new party.
function p.fetch(frame)
	-- Initialise and populate variables
	local args = frame.args
 	local party = stripToNil(args[1]) or error('parameter 1 should be a party name')
	local out_type = stripToNil(args[2]) or error('parameter 2 should be the output type')

	local party_data = getPartyData(party)

	if not next(party_data) then
		return frame.args[1] .. categories.party_not_in_list
	end

	local return_value = party_data[out_type]

	-- If database value doesn't exist, return input (for shortname) or error (for others)
	if return_value == nil then
		if out_type == 'shortname' then
			return args[1]
		else
			return error('Value not in template. Please request that it be added.')
		end
	end

	if out_type == 'color' and string.find(return_value, '#') then
		return_value = string.gsub(return_value, '#', '#')
	end
	return return_value
end

return p