From a0e134ee9dd79761958e62d221f9b6a3cf83ba70 Mon Sep 17 00:00:00 2001 From: Arman Date: Thu, 18 Jul 2024 13:57:47 +0200 Subject: [PATCH] refactor: change base for size calculation --- src/lib/helpers/sizeConvertion.ts | 13 ++++++------- src/lib/helpers/unit.ts | 2 +- 2 files changed, 7 insertions(+), 8 deletions(-) diff --git a/src/lib/helpers/sizeConvertion.ts b/src/lib/helpers/sizeConvertion.ts index 3f9d64621..bd0da8f64 100644 --- a/src/lib/helpers/sizeConvertion.ts +++ b/src/lib/helpers/sizeConvertion.ts @@ -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( diff --git a/src/lib/helpers/unit.ts b/src/lib/helpers/unit.ts index 81b8b4918..9d14b32df 100644 --- a/src/lib/helpers/unit.ts +++ b/src/lib/helpers/unit.ts @@ -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 },