javascript - 重构打字稿中的长函数
问题描述
我有这个功能?我尝试进行一些重构。因此,例如一个通用函数
setSelectedSearchOptions(optionLabel: string) {
//this.filterSection.reset();
this.selectedOption = optionLabel;
this.selectedSearch = optionLabel;
if (optionLabel === 'Registratie') {
this.showDatePickerOne = true;
this.showDatePickerTwo = false;
this.showDatePickerThree = false;
this.buttonFilterDisabled = false;
this.startDate = undefined;
this.selectedValue = '';
this.showDropdownChallenge = false;
this.showDropdownVcheqCode = false;
this.showDropdownMeasurement = false;
this.showDropdownIndicator = false;
}
if (optionLabel === 'Vcheq') {
this.showDatePickerOne = true;
this.showDatePickerTwo = false;
this.showDatePickerThree = false;
this.showDropdownMeasurement = false;
this.isButtonVisible = true;
this.startDate = undefined;
this.showDropdownVcheqCode = true;
this.showDropdownChallenge = false;
this.showDropdownQrCode = false;
this.showDropdownIndicator = false;
}
if (optionLabel === 'Doelen') {
this.showDatePickerOne = true;
this.showDatePickerTwo = false;
this.showDatePickerThree = false;
this.showDropdownMeasurement = false;
this.isButtonVisible = false;
this.startDate = undefined;
this.selectedValue = ',';
this.selectedValueOptie = ',';
this.selectedValueProgressie = ',';
this.showDropdownQrCode = true;
this.showDropdownChallenge = false;
this.showDropdownVcheqCode = false;
this.showDropdownIndicator = false;
}
}
但在我看来,它可以缩短。但我不知道具体如何。
所以我的问题是,如何使这个功能更短?
谢谢
解决方案
您可以将值放在“表”中,例如
const LABELS = ['Registratie', 'Vcheq', 'Doelen'];
const OPTIONS = {
// Registratie Vcheq Doelen
showDatePickerOne: [ 1, 1, 1],
showDatePickerTwo: [ 0, 1, 0],
showDatePickerThree: [ 1, 1, 0],
...etc
};
然后将您的代码替换为
let index = LABELS.indexOf(optionLabel);
for (let [k, v] of Object.entries(OPTIONS)) {
this[k] = v[index];
}
这样,您可以在不失去灵活性的情况下保持代码紧凑。
推荐阅读
- c++ - 通过原子布尔崩溃完成线程
- django - /profile/ 处的 ValueError:“图像”属性没有与之关联的文件
- ios - Swift 乱序执行 firebase 调用
- java - 如何使用 netty 库创建 ssl serversocket
- javascript - VueJs - 使用过渡更改 div 颜色
- ios - 使用 Alamofire 上传带有参数的图像时出现问题
- php - 我想在使用或WhereNull时在以下代码中使用这两个查询我得到错误我如何让我的代码运行
- visual-studio - 使用 Unity 旧版本创建 UWP 应用
- python - 如何使用python从csv逐行打印列表
- python - 网页抓取时如何跳过表格中的某些行