better code: no loop
Massimo Melina committed
Jul 13, 2023 at 15:16 UTC
cc5cfee15c6151494f1b9ae687b0f528e8566763
1 file changed
+2
-9
shared/index.ts
+2
-9
@@ -33,15 +33,8 @@ const MULTIPLIERS = ['', 'K', 'M', 'G', 'T']
33
export function formatBytes(n: number, { post='B', k=1024, digits=NaN }={}) {
34
if (isNaN(Number(n)) || n < 0)
35
return ''
36
- let prevMul = 1
37
- let mul = k
38
- let i = 0
39
- while (i < MULTIPLIERS.length && n > mul) {
40
- prevMul = mul
41
- mul *= k
42
- ++i
43
- }
44
- n /= prevMul
36
+ const i = Math.floor(Math.log2(n) / Math.log2(k))
37
+ n /= k ** i
38
const nAsString = i && !isNaN(digits) ? n.toFixed(digits)
39
: _.round(n, isNaN(digits) ? (n >= 100 ? 0 : 1) : digits)
40
return nAsString + ' ' + (MULTIPLIERS[i]||'') + post