From a0f0699a85ea16e3061ef7e25b5f440c41bc1a5c Mon Sep 17 00:00:00 2001 From: ztimson Date: Wed, 11 Sep 2024 18:33:10 -0400 Subject: [PATCH] Added format bytes helper --- package.json | 2 +- src/string.ts | 8 ++++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index c9ba4f0..609dcdb 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@ztimson/utils", - "version": "0.15.5", + "version": "0.15.6", "description": "Utility library", "author": "Zak Timson", "license": "MIT", diff --git a/src/string.ts b/src/string.ts index fbd0258..e5f64af 100644 --- a/src/string.ts +++ b/src/string.ts @@ -6,6 +6,14 @@ export function createHex(length: number) { return Array(length).fill(null).map(() => Math.round(Math.random() * 0xF).toString(16)).join(''); } +export function formatBytes(bytes: number, decimals = 2) { + if (bytes === 0) return '0 Bytes'; + const k = 1024; + const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; + const i = Math.floor(Math.log(bytes) / Math.log(k)); + return parseFloat((bytes / Math.pow(k, i)).toFixed(decimals)) + ' ' + sizes[i]; +} + /** * String of all letters *