Jump to content

Module:Average change

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Bungle (talk | contribs) at 21:32, 26 July 2024 (create module for calculating average change). 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 p.main(frame)
    local displayType = frame.args[1]
    local params = {tonumber(frame.args[2]), tonumber(frame.args[3]), tonumber(frame.args[4]), tonumber(frame.args[5]), tonumber(frame.args[6])}
    
    -- Filter out nil values
    local values = {}
    for _, v in ipairs(params) do
        if v then
            table.insert(values, v)
        end
    end
    
    -- Error if fewer than 2 valid values
    if #values < 2 then
        return 'Error: Insufficient Parameters'
    end
    
    local changes = {}
    for i = 1, #values - 1 do
        if displayType == "percent" then
            table.insert(changes, ((values[i + 1] - values[i]) / values[i]) * 100)
        else
            table.insert(changes, values[i + 1] - values[i])
        end
    end
    
    -- Calculate average change
    local sum = 0
    for _, change in ipairs(changes) do
        sum = sum + change
    end
    
    local avgChange = sum / #changes
    return string.format("%.2f", avgChange)
end

return p