-- this is a Lua module for working with Tabular Data from Wikimedia Commons. the goal is to consistently display "election results by county" tables
local p =
function sumRow(row) total = 0 for i, j in ipairs(row) do if (i ~= 1) then -- ignore the first entry total = total + j end end return totalend
function electionTable(data) local fileToGet = data or "2020 United States presidential election/Connecticut" local fileFullPath = "Election results/" .. fileToGet .. ".tab" local electionData = mw.ext.data.get(fileFullPath) local electionResults = electionData["data"] local electionSchema = electionData["schema"]["fields"] resultsWikitable = "
" .. electionSchema[1]["title"] for _, schemaRow in ipairs(electionSchema) do if (_ ~= 1) then -- this is to avoid duplicating the county entry resultsWikitable = resultsWikitable .. "\n | " .. schemaRow["title"] end end resultsWikitable = resultsWikitable .. "\n | Total\n | -" for _, schemaRow in ipairs(electionSchema) do if (_ ~= 1) then -- this is to avoid duplicating the county entry resultsWikitable = resultsWikitable .. "\n ! # \n | %" end end for _, resultsRow in ipairs(electionResults) do resultsLocal = "\n | -\n | " .. resultsRow[1] -- start of this row's table syntax and the row's name rowTotal = sumRow(resultsRow) for _, column in ipairs(resultsRow) do if (_ ~= 1) then -- this is to avoid duplicating the county entry resultsLocal = resultsLocal .. " | " .. column -- raw resultsLocal = resultsLocal .. " | " .. math.floor(column*1000/rowTotal)/10 .. "%" -- one decimal of precision end end resultsWikitable = resultsWikitable .. resultsLocal .. " | " .. rowTotal end return resultsWikitable .. "\n |
---|
function p.electionTable(frame) return electionTable(frame.args.data)end
return p