存储大小转换
优化前:
/**
* 将存储大小转换为带单位的字符串
* @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;
}
}
优化内容:
- 添加参数类型检查,确保输入的是数字类型。
- 将计算 MB, GB, TB 的代码重构为一个循环。
- 循环中可以使用一个数组来保存单位名称,避免代码重复