BytesFormatted.tsx 781 B

123456789101112131415161718192021222324252627
  1. import React from 'react';
  2. interface Props {
  3. value: string | number | undefined;
  4. precision?: number;
  5. }
  6. const BytesFormatted: React.FC<Props> = ({ value, precision = 0 }) => {
  7. const formatedValue = React.useMemo(() => {
  8. const bytes = typeof value === 'string' ? parseInt(value, 10) : value;
  9. const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  10. if (!bytes || bytes === 0) return [0, sizes[0]];
  11. if (bytes < 1024) return [Math.ceil(bytes), sizes[0]];
  12. const pow = Math.floor(Math.log2(bytes) / 10);
  13. const multiplier = 10 ** (precision || 2);
  14. return (
  15. Math.round((bytes * multiplier) / 1024 ** pow) / multiplier + sizes[pow]
  16. );
  17. }, [value]);
  18. return <span>{formatedValue}</span>;
  19. };
  20. export default BytesFormatted;