The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
fix(twenty-shared): promote formatBytes to the next unit when rounding reaches 1024 (#28502)
Raphael Fakhri3ffa71331e1d
diff --git a/packages/twenty-shared/src/utils/__tests__/formatBytes.test.ts b/packages/twenty-shared/src/utils/__tests__/formatBytes.test.tsindex 33248a93de3..f0cab71b42e 100644--- a/packages/twenty-shared/src/utils/__tests__/formatBytes.test.ts+++ b/packages/twenty-shared/src/utils/__tests__/formatBytes.test.ts@@ -15,6 +15,16 @@ describe('formatBytes', () => {expect(formatBytes(bytes)).toBe(expected);});+ it('promotes to the next unit when rounding reaches 1024', () => {+ expect(formatBytes(1024 ** 2 - 1)).toBe('1 MB');+ expect(formatBytes(1024 ** 3 - 1)).toBe('1 GB');+ expect(formatBytes(1024 ** 4 - 1)).toBe('1 TB');+ });++ it('does not promote just below a rounding boundary', () => {+ expect(formatBytes(1_048_524)).toBe('1023.9 KB');+ });+it('stays on terabytes past the largest unit', () => {expect(formatBytes(1024 ** 5)).toBe('1024 TB');});diff --git a/packages/twenty-shared/src/utils/format/formatBytes.ts b/packages/twenty-shared/src/utils/format/formatBytes.tsindex 58c2d1d7964..d8dfbd3302c 100644--- a/packages/twenty-shared/src/utils/format/formatBytes.ts+++ b/packages/twenty-shared/src/utils/format/formatBytes.ts@@ -1,11 +1,23 @@const BYTE_UNITS = ['B', 'KB', 'MB', 'GB', 'TB'] as const;+const roundToUnit = ({+ bytes,+ unitIndex,+}: {+ bytes: number;+ unitIndex: number;+}) => Number((bytes / 1024 ** unitIndex).toFixed(unitIndex === 0 ? 0 : 1));+export const formatBytes = (bytes: number): string => {- const unitIndex = Math.min(+ const magnitudeUnitIndex = Math.min(BYTE_UNITS.length - 1,bytes > 0 ? Math.floor(Math.log(bytes) / Math.log(1024)) : 0,);- const scaled = bytes / 1024 ** unitIndex;+ const unitIndex =+ magnitudeUnitIndex < BYTE_UNITS.length - 1 &&+ roundToUnit({ bytes, unitIndex: magnitudeUnitIndex }) >= 1024+ ? magnitudeUnitIndex + 1+ : magnitudeUnitIndex;- return `${Number(scaled.toFixed(unitIndex === 0 ? 0 : 1))} ${BYTE_UNITS[unitIndex]}`;+ return `${roundToUnit({ bytes, unitIndex })} ${BYTE_UNITS[unitIndex]}`;};