BytesFormatted.tsx 987 B

12345678910111213141516171819202122232425262728293031
  1. import React from 'react';
  2. import { NoWrap } from './BytesFormatted.styled';
  3. interface Props {
  4. value: string | number | undefined;
  5. precision?: number;
  6. }
  7. export const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  8. const BytesFormatted: React.FC<Props> = ({ value, precision = 0 }) => {
  9. const formattedValue = React.useMemo((): string => {
  10. try {
  11. const bytes = typeof value === 'string' ? parseInt(value, 10) : value;
  12. if (Number.isNaN(bytes) || (bytes && bytes < 0)) return `-Bytes`;
  13. if (!bytes || bytes < 1024) return `${Math.ceil(bytes || 0)} ${sizes[0]}`;
  14. const pow = Math.floor(Math.log2(bytes) / 10);
  15. const multiplier = 10 ** (precision < 0 ? 0 : precision);
  16. return `${Math.round((bytes * multiplier) / 1024 ** pow) / multiplier} ${
  17. sizes[pow]
  18. }`;
  19. } catch (e) {
  20. return `-Bytes`;
  21. }
  22. }, [precision, value]);
  23. return <NoWrap>{formattedValue}</NoWrap>;
  24. };
  25. export default BytesFormatted;