码率转换
/**
* 码率转换
* @param {number} data 码率值
* @param {string} unit 码率单位
* @param {string} conUnit 转换单位
*/
function transformBitrate(data, unit,conUnit) {
if(unit=='Kbps'){
if(conUnit=='Mbps'){
return (data / (1000)).toFixed(2);
}else if(conUnit=='Gbps'){
return (data / (1000 * 1000)).toFixed(2);
}
}else if(unit=='Mbps'){
if(conUnit=='Gbps'){
return (data / (1000)).toFixed(2);
}else if(conUnit=='Kbps'){
return (data * (1000)).toFixed(2);
}
}else if(unit=='Gbps'){
if(conUnit=='Mbps'){
return (data * 1000).toFixed(2);
}else if(conUnit=='Kbps'){
return (data * 1000 * 1000).toFixed(2);
}
}
return data;
}
优化后:
function transformBitrate(data, unit, conUnit) {
const coefficient = {
Kbps: 1000,
Mbps: 1000 * 1000,
Gbps: 1000 * 1000 * 1000
};
if (unit !== conUnit) {
const result = data * coefficient[unit] / coefficient[conUnit];
return result.toFixed(2);
}
return data;
}
优化:将单位转换的系数提取出来,避免重复计算。同时可以使用对象存储每个单位对应的系数,避免过多的 if 判断。