3



type FileSizeUnitConversionItem = {
  unit: "B" | "KB" | "MB" | "GB" | "T"
  newFileSize: (fileSize: number) => number
}

/** file size 单位转换 对象*/
const fileSizeUnitConversions: FileSizeUnitConversionItem[] = [
  {
    unit: 'B',
    newFileSize: (originalSize: number) => +originalSize.toFixed(2),
  },
  {
    unit: 'KB',
    newFileSize: (originalSize: number) => +parseFloat(String(originalSize / 1024)).toFixed(2),
  },
  {
    unit: 'MB',
    newFileSize: (originalSize: number) => +parseFloat(String(originalSize / Math.pow(1024, 2))).toFixed(2),
  },
  {
    unit: 'GB',
    newFileSize: (originalSize: number) => +parseFloat(String(originalSize / Math.pow(1024, 3))).toFixed(2),
  },
  {
    unit: 'T',
    newFileSize: (originalSize: number) => +parseFloat(String(originalSize / Math.pow(1024, 4))).toFixed(2),
  },
]

/** 获取 file size 单位转换 */
export const getFileSizeUnitConversion = (originalSize: number, unit: string = 'MB') => {
  const newFileSizeItem = fileSizeUnitConversions.find(item => item.unit === unit)
  if (!newFileSizeItem) {
    return
  }
  const fileSizeUnit = newFileSizeItem.unit
  const newFileSize = newFileSizeItem.newFileSize(originalSize)
  console.log('fileSizeUnit', fileSizeUnit);
  console.log('newFileSizeItem', newFileSize);
  return newFileSizeItem
}



白水
1.8k 声望391 粉丝