feat: update deno-commons-mod.ts
This commit is contained in:
@@ -91,20 +91,37 @@ export function formatSize(size: number): string {
|
|||||||
return sizes.reverse().join(" ");
|
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 {
|
export function formatPercent(a: number, b: number): string {
|
||||||
if (b == null || b <= 0) {
|
if (b == null || b <= 0) {
|
||||||
return "N/A";
|
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(".");
|
const pointIndex = p.indexOf(".");
|
||||||
if (pointIndex < 0) {
|
if (pointIndex < 0) {
|
||||||
return p + ".00%";
|
return p + ".00";
|
||||||
}
|
}
|
||||||
const decimal = p.substring(pointIndex + 1);
|
const decimal = p.substring(pointIndex + 1);
|
||||||
const decimalPart = decimal.length == 1
|
const decimalPart = decimal.length == 1
|
||||||
? (decimal + "0")
|
? (decimal + "0")
|
||||||
: decimal.substring(0, 2);
|
: decimal.substring(0, 2);
|
||||||
return p.substring(0, pointIndex) + "." + decimalPart + "%";
|
return p.substring(0, pointIndex) + "." + decimalPart;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function clearLastLine() {
|
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", () => {
|
Deno.test("formatPercent", () => {
|
||||||
assertEquals("N/A", formatPercent(100, -1));
|
assertEquals("N/A", formatPercent(100, -1));
|
||||||
assertEquals("N/A", formatPercent(100, 0));
|
assertEquals("N/A", formatPercent(100, 0));
|
||||||
|
|||||||
Reference in New Issue
Block a user