Skip to content

Commit

Permalink
Merge pull request #120 from sasjs/add-utility-bytesToSize
Browse files Browse the repository at this point in the history
feat: added bytesToSize utility
  • Loading branch information
allanbowe authored Aug 27, 2021
2 parents 8972471 + 16f8292 commit aa0e278
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 0 deletions.
7 changes: 7 additions & 0 deletions src/utils/bytesToSize.spec.ts
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')
})
})
25 changes: 25 additions & 0 deletions src/utils/bytesToSize.ts
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]
}
2 changes: 2 additions & 0 deletions src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,5 @@ export { urlOrigin } from './url'
export { encodeToBase64, decodeFromBase64 } from './base64'

export { getExecutorPath } from './executor'

export { bytesToSize } from './bytesToSize'

0 comments on commit aa0e278

Please sign in to comment.