41 lines
1.0 KiB
JavaScript
41 lines
1.0 KiB
JavaScript
// Formatting helpers for byte counts and transfer rates.
|
|
|
|
const UNITS = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
|
|
const SHORT_UNITS = ['', 'K', 'M', 'G', 'T', 'P'];
|
|
|
|
function scale(n) {
|
|
n = Number(n) || 0;
|
|
let i = 0;
|
|
while (n >= 1024 && i < UNITS.length - 1) {
|
|
n /= 1024;
|
|
i += 1;
|
|
}
|
|
return [n, i];
|
|
}
|
|
|
|
// "2.4 MB", human readable with a space.
|
|
export function formatBytes(n) {
|
|
const [v, i] = scale(n);
|
|
const digits = i === 0 ? 0 : v < 10 ? 1 : v < 100 ? 1 : 0;
|
|
return `${v.toFixed(digits)} ${UNITS[i]}`;
|
|
}
|
|
|
|
// Compact for the panel: "2.4M", "120K", "0".
|
|
export function formatBytesShort(n) {
|
|
const [v, i] = scale(n);
|
|
if (i === 0)
|
|
return `${Math.round(v)}`;
|
|
const digits = v < 10 ? 1 : 0;
|
|
return `${v.toFixed(digits)}${SHORT_UNITS[i]}`;
|
|
}
|
|
|
|
// "2.4 MB/s" for the menu.
|
|
export function formatSpeed(bytesPerSec) {
|
|
return `${formatBytes(bytesPerSec)}/s`;
|
|
}
|
|
|
|
// "2.4M" for the panel (no /s, arrow provides context).
|
|
export function formatSpeedShort(bytesPerSec) {
|
|
return formatBytesShort(bytesPerSec);
|
|
}
|