Software /
code /
prosody
Comparison
util/human/units.lua @ 10889:25e0ec11b4e4
util.human.units: Put math functions into locals
Primarily because the next commit will deal with math.log behaving
differently on Lua 5.1 and that's eaiser with locals.
author | Kim Alvefur <zash@zash.se> |
---|---|
date | Wed, 03 Jun 2020 20:16:00 +0200 |
parent | 10888:42a0d9089de9 |
child | 10890:a451f80d1cea |
comparison
equal
deleted
inserted
replaced
10888:42a0d9089de9 | 10889:25e0ec11b4e4 |
---|---|
1 local math_abs = math.abs; | |
2 local math_ceil = math.ceil; | |
3 local math_floor = math.floor; | |
4 local math_log = math.log; | |
5 local math_max = math.max; | |
6 local math_min = math.min; | |
1 local unpack = table.unpack or unpack; --luacheck: ignore 113 | 7 local unpack = table.unpack or unpack; --luacheck: ignore 113 |
2 | 8 |
3 local large = { | 9 local large = { |
4 "k", 1000, | 10 "k", 1000, |
5 "M", 1000000, | 11 "M", 1000000, |
34 | 40 |
35 -- n: number, the number to format | 41 -- n: number, the number to format |
36 -- unit: string, the base unit | 42 -- unit: string, the base unit |
37 -- b: optional enum 'b', thousands base | 43 -- b: optional enum 'b', thousands base |
38 local function format(n, unit, b) --> string | 44 local function format(n, unit, b) --> string |
39 local round = math.floor; | 45 local round = math_floor; |
40 local prefixes = large; | 46 local prefixes = large; |
41 local logbase = 1000; | 47 local logbase = 1000; |
42 local fmt = "%.3g %s%s"; | 48 local fmt = "%.3g %s%s"; |
43 if n == 0 then | 49 if n == 0 then |
44 return fmt:format(n, "", unit); | 50 return fmt:format(n, "", unit); |
46 if b == 'b' then | 52 if b == 'b' then |
47 prefixes = binary; | 53 prefixes = binary; |
48 logbase = 1024; | 54 logbase = 1024; |
49 elseif n < 1 then | 55 elseif n < 1 then |
50 prefixes = small; | 56 prefixes = small; |
51 round = math.ceil; | 57 round = math_ceil; |
52 end | 58 end |
53 local m = math.max(0, math.min(8, round(math.abs(math.log(math.abs(n), logbase))))); | 59 local m = math_max(0, math_min(8, round(math_abs(math_log(math_abs(n), logbase))))); |
54 local prefix, multiplier = unpack(prefixes, m * 2-1, m*2); | 60 local prefix, multiplier = unpack(prefixes, m * 2-1, m*2); |
55 return fmt:format(n / (multiplier or 1), prefix or "", unit); | 61 return fmt:format(n / (multiplier or 1), prefix or "", unit); |
56 end | 62 end |
57 | 63 |
58 return { | 64 return { |