import { TransformerFunction } from './TransformerFunction';

/**
 * Converts a size in bytes to a human readable string
 * @param bytes size as bytes
 */
export const formatFileSize: TransformerFunction<number, string> = (
  bytes,
): string => {
  if (bytes === null || bytes === undefined) {
    return 'Invalid Value';
  }

  if (bytes === 0 || bytes === null || bytes === undefined) {
    return '0 Bytes';
  }

  const k = 1024,
    units = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];

  let i = 0;

  while (bytes > k) {
    bytes = bytes / k;
    i++;
  }

  return Math.max(bytes).toFixed(2) + ' ' + units[i];
};
