存储大小转换

存储大小转换

优化前:

/**
 * 将存储大小转换为带单位的字符串
 * @param {number} sizeInKB 存储大小(单位:KB)
 * @returns {string|null} 返回带单位的字符串,如果无法转换则返回 null
 */
function transformSize(sizeInKB) {
    var i = parseInt(sizeInKB);
    var mb = (i / (1024)).toFixed(2);
    var gb = (i / (1024 * 1024)).toFixed(2);
    var tb = (i / (1024 * 1024 * 1024)).toFixed(2);
    if (tb > 1) return tb + "T";
    if (gb > 1) return gb + 'G';
    if (mb > 1) return gb + 'M';
    return null;
}

优化后:

/**
 * 将存储大小转换为带单位的字符串
 * @param {number} sizeInKB 存储大小(单位:KB)
 * @returns {string|null} 返回带单位的字符串,如果无法转换则返回 null
 */
function convertToSizeString(sizeInKB) {
  if (typeof sizeInKB !== 'number') {
    throw new TypeError('sizeInKB 参数必须是一个数字');
  }

  const UNITS = ['KB', 'MB', 'GB', 'TB'];
  let size = sizeInKB;
  let unitIndex = 0;
  while (size >= 1024 && unitIndex < UNITS.length - 1) {
    size /= 1024;
    unitIndex++;
  }

  if (unitIndex === 0) {
    return `${size.toFixed(2)}${UNITS[unitIndex]}`;
  } else if (unitIndex < UNITS.length) {
    return `${size.toFixed(2)}${UNITS[unitIndex]}`;
  } else {
    return null;
  }
}

优化内容:

  1. 添加参数类型检查,确保输入的是数字类型。
  2. 将计算 MB, GB, TB 的代码重构为一个循环。
  3. 循环中可以使用一个数组来保存单位名称,避免代码重复
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值