Home > Net >  Selecting current month typescript
Selecting current month typescript

Time:06-09

I have some statements like this

if (newYear < this.currentYear) {
  this.months = this.allMonths.map(value => ({ value, label: value }));
  if (this.selectedMonth) {
    if (!this.allMonths.includes(this.selectedMonth)) {
      this.selectedMonth = undefined;
    }
  }
} else {
  this.months = this.currentYearMonths.map(value => ({ value, label: value }));
  if (this.selectedMonth) {
    if (!this.currentYearMonths.includes(this.selectedMonth)) {
      this.selectedMonth = undefined;
    }
  }
}

The problem is I have so many if , and else, does someone knows how to make it shorter? Thanks

CodePudding user response:

You can extract core part of logic to separate function. Currently looks like it's duplicated. Check helper method:

class A {
  //I am not sure what types are you going to store in those variables, so I type them as any, just to satisfy TS.
  private months: any[] = [];
  private selectedMonth: any = 1;
  private allMonths: any = [];
  private currentYearMonths: any[] = [];

  //extracted helper function, give it some descriptive name
  helper(monthsProp: any[]) {
    this.months = monthsProp.map((value) => ({ value, label: value }));
    if (this.selectedMonth) {
      if (!monthsProp.includes(this.selectedMonth)) {
        this.selectedMonth = undefined;
      }
    }
  }

  yourMainLogic() {
    if (newYear < this.currentYear) {
      this.helper(this.allMonths);
    } else {
      this.helper(this.currentYearMonths);
    }
  }
}

CodePudding user response:

Easy trick is to reverse conditions and return

if (newYear < this.currentYear) {
  this.months = this.allMonths.map(value => ({
    value,
    label: value
  }));
  if (!this.selectedMonth || this.allMonths.includes(this.selectedMonth)) {
    return;
  }
  this.selectedMonth = undefined;
}

if (newYear >= this.currentYear) {
  this.months = this.currentYearMonths.map(value => ({
    value,
    label: value
  }));
  if (!this.selectedMonth || this.currentYearMonths.includes(this.selectedMonth)) {
    return;
  }
  this.selectedMonth = undefined;
}

You can also do return on same line, but I find that less readable:

if (!this.selectedMonth || this.allMonths.includes(this.selectedMonth)) return;

  • Related