Anonymous

Module:Shared: Difference between revisions

From Melvor Idle
formatnum: Use faster variant of function
(Remove joinList: Exists within Scribunto provided libraries as mw.text.listToText; Indent with tabs instead of spaces)
(formatnum: Use faster variant of function)
(2 intermediate revisions by 2 users not shown)
Line 123: Line 123:
function p.tableSort(theTable, sortCol, ascend)
function p.tableSort(theTable, sortCol, ascend)
local new  function sorter(r1, r2)
local new  function sorter(r1, r2)
if(ascend) then
if ascend then
return r1[sortCol] < r2[sortCol]
return r1[sortCol] < r2[sortCol]
else
else
Line 151: Line 151:
end
end
   
   
--Stolen from Stack Overflow
--Adds commas
--Adds commas
function p.formatnum(number)
function p.formatnum(number)
local i, j, minus, int, fraction = tostring(number):find('([-]?)(%d+)([.]?%d*)')
if tonumber(number) == nil then
return number
-- reverse the int-string and append a comma to all blocks of 3 digits
else
int = int:reverse():gsub("(%d%d%d)", "%1,")
local result = number
while true do
-- reverse the int-string back remove an optional comma and put the
-- Format in blocks of 3 digits at a time until formatting is complete
-- optional minus and fractional part back
result, k = string.gsub(result, "^(-?%d+)(%d%d%d)", '%1,%2')
return minus .. int:reverse():gsub("^,", "") .. fraction
if k == 0 then
break
end
end
return result
end
end
end


Line 292: Line 296:
local gcd = p.gcd(n, d)
local gcd = p.gcd(n, d)
return p.formatnum(n/gcd)..'/'..p.formatnum(d/gcd)
return p.formatnum(n/gcd)..'/'..p.formatnum(d/gcd)
end
--Similar to p.fraction but returns the simplified numerator and denomerator separately without formatting
function p.fractionpair(n, d)
local gcd = p.gcd(n, d)
return n / gcd, d / gcd
end
end