Path: blob/1.0-develop/resources/scripts/lib/formatters.ts
7458 views
const _CONVERSION_UNIT = 1024;12/**3* Given a value in megabytes converts it back down into bytes.4*/5function mbToBytes(megabytes: number): number {6return Math.floor(megabytes * _CONVERSION_UNIT * _CONVERSION_UNIT);7}89/**10* Given an amount of bytes, converts them into a human readable string format11* using "1024" as the divisor.12*/13function bytesToString(bytes: number, decimals = 2): string {14const k = _CONVERSION_UNIT;1516if (bytes < 1) return '0 Bytes';1718decimals = Math.floor(Math.max(0, decimals));19const i = Math.floor(Math.log(bytes) / Math.log(k));20const value = Number((bytes / Math.pow(k, i)).toFixed(decimals));2122return `${value} ${['Bytes', 'KiB', 'MiB', 'GiB', 'TiB'][i]}`;23}2425/**26* Formats an IPv4 or IPv6 address.27*/28function ip(value: string): string {29// noinspection RegExpSimplifiable30return /([a-f0-9:]+:+)+[a-f0-9]+/.test(value) ? `[${value}]` : value;31}3233export { ip, mbToBytes, bytesToString };343536