-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #120 from sasjs/add-utility-bytesToSize
feat: added bytesToSize utility
- Loading branch information
Showing
3 changed files
with
34 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
import { bytesToSize } from './bytesToSize' | ||
|
||
describe('bytesToSize', () => { | ||
it('should Convert bytes to KB, MB, GB, TB', () => { | ||
expect(bytesToSize(1024)).toEqual('1.0 KB') | ||
}) | ||
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
/** | ||
* Convert bytes to KB, MB, GB, TB | ||
* @method | ||
* @param {number} bytes amount of bytes | ||
* @param {number} [decimals = 1] amount of digits after decimal point | ||
* @param {number} [maxValue = 1TB] maximum value | ||
* @returns {string} Formatted string representing converted bytes | ||
*/ | ||
export const bytesToSize = ( | ||
bytes: number, | ||
decimals = 1, | ||
maxValue = 1024 * 1024 * 1024 * 1024 // 1TB | ||
) => { | ||
if (bytes === 0) return '0 B' | ||
|
||
bytes = bytes > maxValue ? maxValue : bytes | ||
|
||
const sizes = ['B', 'KB', 'MB', 'GB', 'TB'] | ||
const k = 1024 | ||
const dm = decimals < 0 ? 0 : decimals | ||
|
||
const i = Math.floor(Math.log(bytes) / Math.log(k)) | ||
|
||
return (bytes / Math.pow(k, i)).toFixed(dm) + ' ' + sizes[i] | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters