All files / src/lib/uploads formatUploadProgress.ts

88.88% Statements 8/9
50% Branches 1/2
100% Functions 0/0
88.88% Lines 8/9

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 2962x 62x       610x     16x 16x             313x             8x     305x    
const KIBIBYTE = 1024;
const MEBIBYTE = 1024 * KIBIBYTE;
 
function formatBytesWithUnit(bytes: number, unit: "B" | "KiB" | "MiB"): string {
  if (unit === "B") {
    return `${Math.round(bytes)} B`;
  }
 
  const divisor = unit === "KiB" ? KIBIBYTE : MEBIBYTE;
  return `${(bytes / divisor).toFixed(1)} ${unit}`;
}
 
export function formatUploadProgress(
  uploadedBytes: number,
  totalBytes: number,
): string {
  const referenceBytes = Math.max(uploadedBytes, totalBytes);
 
  if (referenceBytes >= MEBIBYTE) {
    return `${formatBytesWithUnit(uploadedBytes, "MiB")} / ${formatBytesWithUnit(totalBytes, "MiB")}`;
  }
 
  if (referenceBytes >= KIBIBYTE) {
    return `${formatBytesWithUnit(uploadedBytes, "KiB")} / ${formatBytesWithUnit(totalBytes, "KiB")}`;
  }
 
  return `${formatBytesWithUnit(uploadedBytes, "B")} / ${formatBytesWithUnit(totalBytes, "B")}`;
}