summaryrefslogtreecommitdiff
path: root/src/utils/file-size.ts
diff options
context:
space:
mode:
authorrxliuli <rxliuli@gmail.com>2025-11-04 05:03:50 +0800
committerrxliuli <rxliuli@gmail.com>2025-11-04 05:03:50 +0800
commitbce557cc2dc767628bed6aac87301a1be7c5431b (patch)
treeb51a051228d01fe3306cd7626d4a96768aadb944 /src/utils/file-size.ts
init commit
Diffstat (limited to 'src/utils/file-size.ts')
-rw-r--r--src/utils/file-size.ts23
1 files changed, 23 insertions, 0 deletions
diff --git a/src/utils/file-size.ts b/src/utils/file-size.ts
new file mode 100644
index 0000000..f71c4f4
--- /dev/null
+++ b/src/utils/file-size.ts
@@ -0,0 +1,23 @@
+const ROUND_TO = 10;
+const SIZE_INCREMENT = 1000;
+const UNITS = ['byte', 'KB', 'MB', 'GB'];
+
+/**
+ * Converts a byte count into a scaled value with a unit label (e.g. KB, MB, GB).
+ *
+ * @param {number} bytes - The number of bytes.
+ * @returns {{ count: number, unit: string }} Scaled value and its corresponding unit.
+ */
+export function getFileSizeParts(bytes: number) {
+ let index = 0;
+
+ while (bytes >= SIZE_INCREMENT && index < UNITS.length - 1) {
+ bytes /= SIZE_INCREMENT;
+ index++;
+ }
+
+ const count = Math.round(bytes * ROUND_TO) / ROUND_TO;
+ const unit = UNITS[index];
+
+ return { count, unit };
+}