gpt4 book ai didi

javascript - 在 typescript 中重构一个长函数

转载 作者:行者123 更新时间:2023-11-30 10:59:11 25 4
gpt4 key购买 nike

我有这个功能吗?我尝试做一些重构。因此,例如一个通用函数


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;

}
}


但在我看来它可以缩短。但我不知 Prop 体如何。

所以我的问题是,如何让这个函数更短?

谢谢

最佳答案

你可以把这些值放在一个“表”中,比如

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];
}

通过这种方式,您可以在不失去灵 active 的情况下保持代码紧凑。

关于javascript - 在 typescript 中重构一个长函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58624993/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com