From c680fbd1f9e31562625df5587392fc470eaac132 Mon Sep 17 00:00:00 2001 From: Alex Yong Date: Thu, 25 Apr 2024 20:50:40 +0000 Subject: [PATCH] Putting the format size stuff in a common function --- frontend/src/stores/upload.ts | 29 ++++++++++++++--------------- 1 file changed, 14 insertions(+), 15 deletions(-) diff --git a/frontend/src/stores/upload.ts b/frontend/src/stores/upload.ts index 7ef5c6af..7738a261 100644 --- a/frontend/src/stores/upload.ts +++ b/frontend/src/stores/upload.ts @@ -13,6 +13,15 @@ const beforeUnload = (event: Event) => { // event.returnValue = ""; }; +// Utility function to format bytes into a readable string +function formatSize(bytes: number): string { + if (bytes === 0) return '0 Bytes'; + + const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; + const i = Math.floor(Math.log(bytes) / Math.log(1024)); + return parseFloat((bytes / Math.pow(1024, i)).toFixed(2)) + ' ' + sizes[i]; +} + export const useUploadStore = defineStore("upload", { // convert to a function state: (): { @@ -59,29 +68,19 @@ export const useUploadStore = defineStore("upload", { return ((sum / totalSize) * 100).toFixed(2); }, getTotalProgressBytes: (state) => { - if (state.progress.length === 0 || state.sizes.length === 0) { + if (state.progress.length === 0 || state.sizes.length === 0) { return '0 Bytes'; } - - const totalSize = state.sizes.reduce((a, b) => a + b, 0); - - // TODO: this looks ugly but it works with ts now - const sum = state.progress.reduce((acc, val) => +acc + +val) as number; - const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; - const i = Math.floor(Math.log(sum) / Math.log(1024)); - return parseFloat((sum / Math.pow(1024, i)).toFixed(2)) + ' ' + sizes[i]; - + const sum = state.progress.reduce((acc, val) => +acc + +val, 0) as number; + return formatSize(sum); }, getTotalSize: (state) => { if (state.sizes.length === 0) { return '0 Bytes'; } - const totalSize = state.sizes.reduce((a, b) => a + b, 0); - const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; - const i = Math.floor(Math.log(totalSize) / Math.log(1024)); - return parseFloat((totalSize / Math.pow(1024, i)).toFixed(2)) + ' ' + sizes[i]; - }, + return formatSize(totalSize); + }, filesInUploadCount: (state) => { return Object.keys(state.uploads).length + state.queue.length; },