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 17:28, 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 = {}
	local monthlyLow = {}
	local percipSum = {0,0,0,0,0,0,0,0,0,0,0,0}
	local percipCount = {0,0,0,0,0,0,0,0,0,0,0,0}

	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 > -99 and (monthlyHigh[month] == nil or monthlyHigh[month] < tempHigh) then monthlyHigh[month] = tempHigh end
		if tempLow > -99 and (monthlyLow[month] == nil or monthlyLow[month] > tempLow) then monthlyLow[month] = tempLow end
		if percip > -99 then
			percipSum[month] = percipSum[month] + percip
			percipCount[month] = percipCount[month] + 1
		end
	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] .. ' precipitation inch'] = string.format("%.1f", percipSum[i] / percipCount[i]) end

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

function p.dbg( frame )
	return mw.text.jsonEncode( p._impl('Weather/New York City.tab') )
end

function highest(tbl, comparator)
    if #tbl == 0 then return nil end
    local value = tbl[1]
    for i = 2, #tbl do
        if comparator(value, tbl[i]) then
            value = tbl[i]
        end
    end
    return value
end

return p