Module:Average change: Difference between revisions
Appearance
Content deleted Content added
create module for calculating average change |
updated code |
||
Line 1: | Line 1: | ||
local p = {} |
local p = {} |
||
function |
-- Main function to calculate average change |
||
function p.main(displayType, omitOperator, ...) |
|||
-- Collect all variable arguments into a table |
|||
local params = {tonumber(frame.args[2]), tonumber(frame.args[3]), tonumber(frame.args[4]), tonumber(frame.args[5]), tonumber(frame.args[6])} |
|||
local params = {...} |
|||
-- Filter out nil values |
-- Filter out nil values and convert to numbers |
||
local values = {} |
local values = {} |
||
for _, v in ipairs(params) do |
for _, v in ipairs(params) do |
||
v = tonumber(v) |
|||
if v then |
if v then |
||
table.insert(values, v) |
table.insert(values, v) |
||
Line 15: | Line 17: | ||
-- Error if fewer than 2 valid values |
-- Error if fewer than 2 valid values |
||
if #values < 2 then |
if #values < 2 then |
||
return 'Error: Insufficient |
return 'Error: Insufficient parameters' |
||
end |
end |
||
-- Calculate changes |
|||
local changes = {} |
local changes = {} |
||
for i = 1, #values - 1 do |
for i = 1, #values - 1 do |
||
Line 34: | Line 37: | ||
local avgChange = sum / #changes |
local avgChange = sum / #changes |
||
local formattedChange = string.format("%.2f", avgChange) |
|||
-- Omit the operator if specified |
|||
if omitOperator == "yes" then |
|||
formattedChange = string.gsub(formattedChange, "^%-", "") |
|||
end |
|||
return formattedChange |
|||
end |
end |
||
Revision as of 07:16, 27 July 2024
local p = {}
-- Main function to calculate average change
function p.main(displayType, omitOperator, ...)
-- Collect all variable arguments into a table
local params = {...}
-- Filter out nil values and convert to numbers
local values = {}
for _, v in ipairs(params) do
v = tonumber(v)
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
-- Calculate changes
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
local formattedChange = string.format("%.2f", avgChange)
-- Omit the operator if specified
if omitOperator == "yes" then
formattedChange = string.gsub(formattedChange, "^%-", "")
end
return formattedChange
end
return p