Merge pull request #1210 from appwrite/refactor-change-file-sizes-base

refactor: change base for size calculation
This commit is contained in:
Torsten Dittmann
2024-07-18 18:34:20 +02:00
committed by GitHub
2 changed files with 7 additions and 8 deletions
+6 -7
View File
@@ -3,25 +3,24 @@ import prettyBytes from 'pretty-bytes';
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'] as const;
export type Size = (typeof sizes)[number];
export function calculateSize(bytes: number, decimals = 1) {
export function calculateSize(bytes: number, decimals = 1, base: 1000 | 1024 = 1000) {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
const i = Math.floor(Math.log(bytes) / Math.log(k));
const i = Math.floor(Math.log(bytes) / Math.log(base));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
return parseFloat((bytes / Math.pow(base, i)).toFixed(dm)) + ' ' + sizes[i];
}
export function sizeToBytes(value: number, unit: Size, base = 1024) {
export function sizeToBytes(value: number, unit: Size, base = 1000) {
const index = sizes.indexOf(unit);
return value * Math.pow(base, index);
}
export function bytesToSize(value: number, unit: Size) {
export function bytesToSize(value: number, unit: Size, base = 1000) {
const index = sizes.indexOf(unit);
return value / Math.pow(1024, index);
return value / Math.pow(base, index);
}
export function humanFileSize(
+1 -1
View File
@@ -73,7 +73,7 @@ export function createTimeUnitPair(initialValue = 0) {
return { ...createValueUnitPair(initialValue, units), units };
}
export function createByteUnitPair(initialValue = 0, base = 1024) {
export function createByteUnitPair(initialValue = 0, base: 1000 | 1024 = 1000) {
const units: Unit[] = [
{ name: 'Bytes', value: 1 },
{ name: 'Kilobytes', value: base },