Putting the format size stuff in a common function

This commit is contained in:
Alex Yong 2024-04-25 20:50:40 +00:00
parent 9102678f69
commit c680fbd1f9

View File

@ -13,6 +13,15 @@ const beforeUnload = (event: Event) => {
// event.returnValue = ""; // 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", { export const useUploadStore = defineStore("upload", {
// convert to a function // convert to a function
state: (): { state: (): {
@ -59,28 +68,18 @@ export const useUploadStore = defineStore("upload", {
return ((sum / totalSize) * 100).toFixed(2); return ((sum / totalSize) * 100).toFixed(2);
}, },
getTotalProgressBytes: (state) => { getTotalProgressBytes: (state) => {
if (state.progress.length === 0 || state.sizes.length === 0) { if (state.progress.length === 0 || state.sizes.length === 0) {
return '0 Bytes'; return '0 Bytes';
} }
const sum = state.progress.reduce((acc, val) => +acc + +val, 0) as number;
const totalSize = state.sizes.reduce((a, b) => a + b, 0); return formatSize(sum);
// 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];
}, },
getTotalSize: (state) => { getTotalSize: (state) => {
if (state.sizes.length === 0) { if (state.sizes.length === 0) {
return '0 Bytes'; return '0 Bytes';
} }
const totalSize = state.sizes.reduce((a, b) => a + b, 0); const totalSize = state.sizes.reduce((a, b) => a + b, 0);
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; return formatSize(totalSize);
const i = Math.floor(Math.log(totalSize) / Math.log(1024));
return parseFloat((totalSize / Math.pow(1024, i)).toFixed(2)) + ' ' + sizes[i];
}, },
filesInUploadCount: (state) => { filesInUploadCount: (state) => {
return Object.keys(state.uploads).length + state.queue.length; return Object.keys(state.uploads).length + state.queue.length;