是否有其他方法可以优化此功能或更好的方法



我用react写了一个函数,它正常工作,正如预期的那样。我唯一的问题是,是否有其他方法可以优化它,只是为了可读性和更好地接近

这是我的代码:

export const formatter = (num, lastDigit = 3) => {
if (num.length === 13) {
return `xxxx xxxx xx ${num.substr(num.length - lastDigit)}`;
} else if (num.length === 14) {
return `xxxx xxxx xxx ${num.substr(num.length - lastDigit)}`;
} else {
return `xxxx xxxx xxxx ${num.substr(num.length - lastDigit)}`;
}
};

为了可读性:

  • 将重复代码移动到常量
  • 使用switch而不是if/else更容易读取,因为更容易看到逻辑处理单个值的不同选项
export const formatter = (num, lastDigit = 3) => {
const value = num.substr(num.length - lastDigit);
switch(num.length) {
case 13:
return `xxxx xxxx xx ${value}`;
case 14:
return `xxxx xxxx xxx ${value}`;
default:
return `xxxx xxxx xxxx ${value}`;
};
};

为了更好的可读性,您可以尝试以下方法:

export const formatter = (num, lastDigit = 3) => {
const length = num.length;
const subString = num.substr(num.length - lastDigit);

if (length === 13) {
return `xxxx xxxx xx ${subString}`;
} else if (num.length === 14) {
return `xxxx xxxx xxx ${subString}`;
} else {
return `xxxx xxxx xxxx ${subString}`;
}
};

最新更新