Jump to content

Module:Election box US auto

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Legoktm (talk | contribs) at 10:36, 11 November 2018 (Created page with 'local p = {} function get_candidates( contest ) -- TODO: parameterize year and election local data = mw.ext.data.get("California Elections/2016 Presidential G...'). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
(diff) ← Previous revision | Latest revision (diff) | Newer revision → (diff)

local p = {}

function get_candidates( contest )
	-- TODO: parameterize year and election
	local data = mw.ext.data.get("California Elections/2016 Presidential General/Candidates.tab").data
	local candidates = {}
	for k,v in pairs(data) do
		if v[1] == contest then
			table.insert(candidates, v)
		end
	end
	
	return candidates
end

function percent( part, total )
	return mw.ext.ParserFunctions.expr( "" .. 100 * part / total .. " round 1" )
end

function p.make( frame )
	return make( frame.args[1] )
end

function make( contest )
	local candidates = get_candidates( contest )
	local total_votes = 0
	local winner = {}
	winner[5] = 0
	for k,v in pairs(candidates) do
		total_votes = total_votes + v[5]
		if v[5] > winner[5] then
			winner = v
		end
	end
	local ret = "{{Election box begin no change| title=[[United States House of Representatives elections, 2016]]}}"
	function sort_candidates(a,b)
		return a[5] < b[5]
	end
	table.sort(candidates, sort_candidates)
	for k,v in pairs(candidates) do
		local temp = "{{"
		if v[2] == winner[2] then
			temp = temp .. "Election box winning candidate"
		else
			temp = temp .. "Election box candidate"
		end
		local n_party = normalize_parties( v[3] )
		if n_party then
			temp = temp .. " with party link no change|party=" .. n_party
		else
			temp = temp .. " no party link no change"
		end
		-- FIXME: disambiguators???
		temp = temp .. "|candidate=[[" .. v[2] .. "]]"
		if v[4] then
			-- incumbent
			temp  = temp .. " ([[incumbent]])"
		end
		temp = temp .. "|votes={{formatnum:" .. v[5] .. "}}"
		temp = temp .. "|percentage=" .. percent(v[5], total_votes) .. "%"
		temp = temp .. "}}"
		ret = ret .. temp
	end
	ret = ret .. "{{Election box total no change|votes= {{formatnum:" .. total_votes .. "}}|percentage = 100.0%}}"
	-- FIXME: implement {{Election box hold with party link without swing}}?
	ret = ret .. "{{Election box end}}"
	return ret
end

function normalize_parties( party )
	-- TODO: comma split for multi-party candidates
	local parties = {
		Democratic = "Democratic Party (United States)",
		Republican = "Republican Party (United States)"
	}
	
	for k, v in pairs(parties) do
		if k == party then
			return v
		end
	end
	-- not found, return false
	return false
end

return p