首页 > 解决方案 > 重构打字稿中的长函数

问题描述

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


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;

    }
}


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

所以我的问题是,如何使这个功能更短?

谢谢

标签: javascriptangulartypescript

解决方案


您可以将值放在“表”中,例如

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

这样,您可以在不失去灵活性的情况下保持代码紧凑。


推荐阅读