diff --git a/packages/auto-consensus/src/utils/format.ts b/packages/auto-consensus/src/utils/format.ts new file mode 100644 index 0000000..30a629b --- /dev/null +++ b/packages/auto-consensus/src/utils/format.ts @@ -0,0 +1,25 @@ +// Binary format (powers of 2) +export const formatSpaceToBinary = (value: number, decimals = 2) => { + if (value === 0) return '0 Bytes' + + const k = 1024 + const dm = decimals < 0 ? 0 : decimals + const sizes = ['Bytes', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'] + + const i = Math.floor(Math.log(value) / Math.log(k)) + + return parseFloat((value / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i] +} + +// Decimal format (powers of 10) +export const formatSpaceToDecimal = (value: number, decimals = 2) => { + if (value === 0) return '0 Bytes' + + const k = 1000 + const dm = decimals < 0 ? 0 : decimals + const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'] + + const i = Math.floor(Math.log(value) / Math.log(k)) + + return parseFloat((value / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i] +} diff --git a/packages/auto-consensus/src/utils/index.ts b/packages/auto-consensus/src/utils/index.ts index 01631cc..6abc4b7 100644 --- a/packages/auto-consensus/src/utils/index.ts +++ b/packages/auto-consensus/src/utils/index.ts @@ -1,6 +1,7 @@ // file: src/utils/index.ts export * from './events' +export * from './format' export * from './parse' export * from './query' export * from './sudo'