Jump to content

Module:Sandbox/Yurik

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Yurik (talk | contribs) at 20:44, 9 December 2016. The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
local p = {}
local getArgs = require('Module:Arguments').getArgs
local datePattern = "^(%d+)-(%d+)-(%d+)$"
local weatherTemplate = 'Template:Weather box'
local wrapsTemplate = 'User:Yurik/Weather box'

function p.weatherbox( frame )
    local args = getArgs(frame, { wrappers = wrapsTemplate })
    local dataPage = assert(args.data, 'Missing "data" parameter')
    args.data = nil

    local monthlyHigh, monthlyLow = {}, {}
    local highSum, highCount = {}, {}
    local lowSum, lowCount = {}, {}
    local percipSum, percipCount = {}, {}

    for key, row in pairs(mw.ext.data.get(dataPage).data) do
        -- First column is in [0], not [1], needs special handling
        local date = row[0]
        local percip, tempLow, tempAvg, tempHigh = unpack(row)

        local year, month, day = date:match(datePattern)
        month = tonumber(month)
        if tempHigh > -999 and (monthlyHigh[month] == nil or monthlyHigh[month] < tempHigh) then monthlyHigh[month] = tempHigh end
        if tempLow > -999 and (monthlyLow[month] == nil or monthlyLow[month] > tempLow) then monthlyLow[month] = tempLow end
        recordAvg(percipSum, percipCount, month, percip)
        recordAvg(highSum, highCount, month, tempHigh)
        recordAvg(lowSum, lowCount, month, tempLow)
    end

    local months = {'Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'}
    for i=1, 12 do args[months[i] .. ' record high F'] = monthlyHigh[i] end
    for i=1, 12 do args[months[i] .. ' record low F'] = monthlyLow[i] end
    for i=1, 12 do args[months[i] .. ' avg record high F'] = string.format("%.1f", highSum[i] / highCount[i]) end
    for i=1, 12 do args[months[i] .. ' avg record low F'] = string.format("%.1f", lowSum[i] / lowCount[i]) end
    for i=1, 12 do args[months[i] .. ' precipitation inch'] = string.format("%.1f", percipSum[i] / percipCount[i]) end

    return frame:expandTemplate{ title = weatherTemplate, args = args }
end

function recordAvg(sumTbl, countTbl, month, value)
    if value > -999 then
        sumTbl[month] = (sumTbl[month] or 0) + value
        countTbl[month] = (countTbl[month] or 0) + 1
    end
end

return p