formatTransferBytes (util/transfer-format.ts)

imcodes · web/src/util/transfer-format.ts · typescript · MIT
ui, tag:knn-classified

Utility to format file sizes and durations for transfer displays.

// Source: https://github.com/im4codes/imcodes | License: MIT | Copyright 2026 IM.codes
// Provided via justclaw.it.com; keep this notice with the code.
export function formatTransferBytes(bytes: number): string {
  const safeBytes = Math.max(0, Number.isFinite(bytes) ? bytes : 0);
  const units: Array<{ size: number; unit: Intl.NumberFormatOptions['unit'] }> = [
    { size: 1024 ** 4, unit: 'terabyte' },
    { size: 1024 ** 3, unit: 'gigabyte' },
    { size: 1024 ** 2, unit: 'megabyte' },
    { size: 1024, unit: 'kilobyte' },
    { size: 1, unit: 'byte' },
  ];
  const selected = units.find((entry) => safeBytes >= entry.size) ?? units[units.length - 1];
  return new Intl.NumberFormat(undefined, {
    style: 'unit',
    unit: selected.unit,
    unitDisplay: 'short',
    maximumFractionDigi

... (truncated -- full source via MCP)

See the full source, get the GitHub permalink, and search for more like it.

Get a free API key