Skip to content

Commit

Permalink
refactor: getFileSizeToClosestByte
Browse files Browse the repository at this point in the history
  • Loading branch information
rpenido committed Jan 12, 2024
1 parent ae9657d commit a86f597
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 16 deletions.
25 changes: 9 additions & 16 deletions src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -257,21 +257,14 @@ export const isValidDate = (date) => {
return Boolean(formattedValue.length <= 10);
};

export const getFileSizeToClosestByte = (fileSize, numberOfDivides = 0) => {
if (fileSize > 1000) {
const updatedSize = fileSize / 1000;
const incrementNumberOfDivides = numberOfDivides + 1;
return getFileSizeToClosestByte(updatedSize, incrementNumberOfDivides);
}
const fileSizeFixedDecimal = Number.parseFloat(fileSize).toFixed(2);
switch (numberOfDivides) {
case 1:
return `${fileSizeFixedDecimal} KB`;
case 2:
return `${fileSizeFixedDecimal} MB`;
case 3:
return `${fileSizeFixedDecimal} GB`;
default:
return `${fileSizeFixedDecimal} B`;
export const getFileSizeToClosestByte = (fileSize) => {
let divides = 0;
let size = fileSize;
while (size > 1000 && divides < 4) {
size /= 1000;
divides += 1;
}
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
const fileSizeFixedDecimal = Number.parseFloat(size).toFixed(2);
return `${fileSizeFixedDecimal} ${units[divides]}`;
};
10 changes: 10 additions & 0 deletions src/utils.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,5 +22,15 @@ describe('FilesAndUploads utils', () => {
const actualSize = getFileSizeToClosestByte(2034190000);
expect(expectedSize).toEqual(actualSize);
});
it('should return file size with TB for terabytes', () => {
const expectedSize = '1.99 TB';
const actualSize = getFileSizeToClosestByte(1988034190000);
expect(expectedSize).toEqual(actualSize);
});
it('should return file size with TB for larger numbers', () => {
const expectedSize = '1234.56 TB';
const actualSize = getFileSizeToClosestByte(1234560000000000);
expect(expectedSize).toEqual(actualSize);
});
});
});

0 comments on commit a86f597

Please sign in to comment.