From 2cdf84b1d1e9acef6d4b538dd65e8a72400b4d15 Mon Sep 17 00:00:00 2001 From: Hatter Jiang Date: Sun, 19 Jan 2025 12:47:46 +0800 Subject: [PATCH] feat: update deno-commons-mod.ts --- libraries/deno-commons-mod.ts | 70 +++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) diff --git a/libraries/deno-commons-mod.ts b/libraries/deno-commons-mod.ts index 450a3fa..bc4d4c2 100644 --- a/libraries/deno-commons-mod.ts +++ b/libraries/deno-commons-mod.ts @@ -62,6 +62,51 @@ export function formatHumanTime(timeMillis: number): string { return times.reverse().join(" "); } +export function formatSize(size: number): string { + if (size < 0) { + return "N/A"; + } + if (size == 0) { + return "0B"; + } + const sizes = []; + const bytesLow = size % 1024; + if (bytesLow > 0) { + sizes.push(`${bytesLow}B`); + } + const kb = Math.floor(size / 1024); + const kbLow = kb % 1024; + if (kbLow > 0) { + sizes.push(`${kbLow}KiB`); + } + const mb = Math.floor(kb / 1024); + const mbLow = mb % 1024; + if (mbLow > 0) { + sizes.push(`${mbLow}MiB`); + } + const gb = Math.floor(mb / 1024); + if (gb > 0) { + sizes.push(`${gb}GiB`); + } + return sizes.reverse().join(" "); +} + +export function formatPercent(a: number, b: number): string { + if (b == null || b <= 0) { + return "N/A"; + } + const p = ((a * 100) / b).toString(); + const pointIndex = p.indexOf("."); + if (pointIndex < 0) { + 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 + "%"; +} + Deno.test("isOn", () => { assertEquals(false, isOn(undefined)); assertEquals(false, isOn("")); @@ -85,3 +130,28 @@ Deno.test("formatHumanTime", () => { assertEquals("1h 1s", formatHumanTime(3601000)); assertEquals("1h 1m 1s", formatHumanTime(3661000)); }); + +Deno.test("formatSize", () => { + assertEquals("N/A", formatSize(-1)); + assertEquals("0B", formatSize(0)); + assertEquals("1B", formatSize(1)); + assertEquals("1KiB", formatSize(1024)); + assertEquals("1KiB 1B", formatSize(1024 + 1)); + assertEquals("1MiB 1KiB 1B", formatSize(1024 * 1024 + 1024 + 1)); + assertEquals( + "1GiB 1MiB 1KiB 1B", + formatSize(1024 * 1024 * 1024 + 1024 * 1024 + 1024 + 1), + ); +}); + +Deno.test("formatPercent", () => { + assertEquals("N/A", formatPercent(100, -1)); + assertEquals("N/A", formatPercent(100, 0)); + assertEquals("N/A", formatPercent(100, 0)); + assertEquals("10.00%", formatPercent(10, 100)); + assertEquals("11.00%", formatPercent(11, 100)); + assertEquals("1.10%", formatPercent(11, 1000)); + assertEquals("0.10%", formatPercent(1, 1000)); + assertEquals("0.00%", formatPercent(1, 100000)); + assertEquals("100.00%", formatPercent(100, 100)); +});