2022-06-27 22:46:36 +00:00
|
|
|
const _CONVERSION_UNIT = 1024;
|
2022-06-26 18:34:09 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Given a value in megabytes converts it back down into bytes.
|
|
|
|
*/
|
2022-06-26 19:13:52 +00:00
|
|
|
function mbToBytes(megabytes: number): number {
|
2022-06-26 18:34:09 +00:00
|
|
|
return Math.floor(megabytes * _CONVERSION_UNIT * _CONVERSION_UNIT);
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Given an amount of bytes, converts them into a human readable string format
|
2022-06-27 22:46:36 +00:00
|
|
|
* using "1024" as the divisor.
|
2022-06-26 18:34:09 +00:00
|
|
|
*/
|
2022-06-27 22:46:36 +00:00
|
|
|
function bytesToString(bytes: number, decimals = 2): string {
|
|
|
|
const k = _CONVERSION_UNIT;
|
|
|
|
|
2022-06-26 18:34:09 +00:00
|
|
|
if (bytes < 1) return '0 Bytes';
|
|
|
|
|
2022-06-27 22:46:36 +00:00
|
|
|
decimals = Math.floor(Math.max(0, decimals));
|
|
|
|
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
|
|
|
const value = Number((bytes / Math.pow(k, i)).toFixed(decimals));
|
2022-06-26 18:34:09 +00:00
|
|
|
|
2022-06-26 19:13:52 +00:00
|
|
|
return `${value} ${['Bytes', 'KB', 'MB', 'GB', 'TB'][i]}`;
|
2022-06-26 18:34:09 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Formats an IPv4 or IPv6 address.
|
|
|
|
*/
|
2022-06-26 19:13:52 +00:00
|
|
|
function ip(value: string): string {
|
2022-06-26 18:34:09 +00:00
|
|
|
// noinspection RegExpSimplifiable
|
|
|
|
return /([a-f0-9:]+:+)+[a-f0-9]+/.test(value) ? `[${value}]` : value;
|
|
|
|
}
|
|
|
|
|
2022-06-26 19:13:52 +00:00
|
|
|
export { ip, mbToBytes, bytesToString };
|