Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
pterodactyl
GitHub Repository: pterodactyl/panel
Path: blob/1.0-develop/resources/scripts/lib/formatters.ts
7458 views
1
const _CONVERSION_UNIT = 1024;
2
3
/**
4
* Given a value in megabytes converts it back down into bytes.
5
*/
6
function mbToBytes(megabytes: number): number {
7
return Math.floor(megabytes * _CONVERSION_UNIT * _CONVERSION_UNIT);
8
}
9
10
/**
11
* Given an amount of bytes, converts them into a human readable string format
12
* using "1024" as the divisor.
13
*/
14
function bytesToString(bytes: number, decimals = 2): string {
15
const k = _CONVERSION_UNIT;
16
17
if (bytes < 1) return '0 Bytes';
18
19
decimals = Math.floor(Math.max(0, decimals));
20
const i = Math.floor(Math.log(bytes) / Math.log(k));
21
const value = Number((bytes / Math.pow(k, i)).toFixed(decimals));
22
23
return `${value} ${['Bytes', 'KiB', 'MiB', 'GiB', 'TiB'][i]}`;
24
}
25
26
/**
27
* Formats an IPv4 or IPv6 address.
28
*/
29
function ip(value: string): string {
30
// noinspection RegExpSimplifiable
31
return /([a-f0-9:]+:+)+[a-f0-9]+/.test(value) ? `[${value}]` : value;
32
}
33
34
export { ip, mbToBytes, bytesToString };
35
36