feat: update deno-commons-mod.ts

This commit is contained in:
2025-01-19 13:05:33 +08:00
parent de2b03a047
commit 5740a56dc5

View File

@@ -1,7 +1,7 @@
// Reference:
// - https://docs.deno.com/runtime/fundamentals/testing/
import { assertEquals } from "jsr:@std/assert";
import {assertEquals} from "jsr:@std/assert";
export function compareVersion(ver1: string, ver2: string): 0 | 1 | -1 {
if (ver1 === ver2) return 0;
@@ -91,20 +91,37 @@ export function formatSize(size: number): string {
return sizes.reverse().join(" ");
}
export function formatSize2(size: number): string {
if (size < 0) {
return "N/A";
}
if (size < 1024) {
return `${size}B`;
}
if (size < 1024 * 1024) {
return `${formatNumber(size / 1024)}KiB`;
}
return `${formatNumber(size / (1024 * 1024))}MiB`;
}
export function formatPercent(a: number, b: number): string {
if (b == null || b <= 0) {
return "N/A";
}
const p = ((a * 100) / b).toString();
return formatNumber((a * 100) / b) + "%";
}
export function formatNumber(num: number): string {
const p = num.toString();
const pointIndex = p.indexOf(".");
if (pointIndex < 0) {
return p + ".00%";
return p + ".00";
}
const decimal = p.substring(pointIndex + 1);
const decimalPart = decimal.length == 1
? (decimal + "0")
: decimal.substring(0, 2);
return p.substring(0, pointIndex) + "." + decimalPart + "%";
return p.substring(0, pointIndex) + "." + decimalPart;
}
export async function clearLastLine() {
@@ -156,6 +173,15 @@ Deno.test("formatSize", () => {
);
});
Deno.test("formatSize2", () => {
assertEquals("N/A", formatSize2(-1));
assertEquals("0B", formatSize2(0));
assertEquals("1B", formatSize2(1));
assertEquals("1.00KiB", formatSize2(1024));
assertEquals("10.00KiB", formatSize2(1024 * 10));
assertEquals("1.00MiB", formatSize2(1024 * 1024));
});
Deno.test("formatPercent", () => {
assertEquals("N/A", formatPercent(100, -1));
assertEquals("N/A", formatPercent(100, 0));