feat: add vitest pkg, formatBytes lib function with tests

This commit is contained in:
2025-07-12 21:27:28 -05:00
parent df988fb670
commit 0f5558ec11
6 changed files with 962 additions and 7 deletions

View File

@@ -23,6 +23,7 @@
"@types/react-dom": "^18.0.6",
"@vitejs/plugin-react": "^2.0.1",
"typescript": "^4.6.4",
"vite": "^3.0.7"
"vite": "^3.0.7",
"vitest": "^3.2.4"
}
}

View File

@@ -1 +1 @@
09087dfd9742bacd550951060ae8f28f
435a9196aacc1e4aa5eb43cd8621ad0e

896
frontend/pnpm-lock.yaml generated
View File

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,2 @@
onlyBuiltDependencies:
- esbuild

View File

@@ -0,0 +1,28 @@
import { formatBytes } from "./format.js";
import { test, expect } from "vitest";
test("formats bytes less than 1024", () => {
expect(formatBytes(512)).toBe("512 B");
});
test("formats KiB correctly", () => {
expect(formatBytes(2048)).toBe("2 KiB");
expect(formatBytes(1536)).toBe("1.5 KiB");
expect(formatBytes(1024)).toBe("1 KiB");
});
test("formats MiB correctly", () => {
expect(formatBytes(1048576)).toBe("1 MiB");
expect(formatBytes(1572864)).toBe("1.5 MiB");
expect(formatBytes(2097152)).toBe("2 MiB");
});
test("formats GiB correctly", () => {
expect(formatBytes(1073741824)).toBe("1 GiB");
expect(formatBytes(1610612736)).toBe("1.5 GiB");
expect(formatBytes(2147483648)).toBe("2 GiB");
});
test("formats large values with no decimal if intValue >= 1000", () => {
expect(formatBytes(1024 * 1024 * 1000)).toBe("1000 MiB");
});

View File

@@ -0,0 +1,38 @@
/**
* Formats a number of bytes into a human-readable string using binary units (KiB, MiB, GiB, TiB).
*
* - For values less than 1024, returns the value in bytes (e.g., "512 B").
* - For larger values, converts to the appropriate unit and formats:
* - If the integer part is 1000 or more, shows no decimal (e.g., "1024 KiB").
* - If the decimal part is at least 0.1, shows one decimal place (e.g., 1228.8 KiB formats as "1.2 MiB").
* - Otherwise, shows no decimal (e.g., 1075.2 MiB == 1.05 GiB, formats as "1 GiB").
*
* @param v - The number of bytes to format.
* @returns The formatted string with the appropriate unit.
*/
export function formatBytes(v: number): string {
if (v < 1024) return `${v} B`;
const units = ["KiB", "MiB", "GiB", "TiB"];
let unitIndex = -1;
let value = v;
while (value >= 1024 && unitIndex < units.length - 1) {
value /= 1024;
unitIndex++;
}
const intValue = Math.floor(value);
const decimal = value - intValue;
if (intValue >= 1000) {
// More than 3 digits, no decimal
return `${intValue} ${units[unitIndex]}`;
} else if (decimal >= 0.1) {
// Show 1 decimal if decimal >= 0.1
return `${value.toFixed(1)} ${units[unitIndex]}`;
} else {
// No decimal
return `${intValue} ${units[unitIndex]}`;
}
}