NiceToMytyuk
NiceToMytyuk

Reputation: 4277

How to build return statement dynamically in typescript?

I need to set a return value to a variable dynamically with values get from an API.

The function looks like this with static values:

this.markDisabled = (date: NgbDate) => {
  return (this.calendar.getWeekday(date) !== 5 && this.calendar.getWeekday(date) !== 1);
};

But actually the !== 5 and !== 1 must be set dynamically and there could be only one parameter or up to seven.

So if my API returns values like 3,5,6 i need to build the function as the following:

this.markDisabled = (date: NgbDate) => {
  return (this.calendar.getWeekday(date) !== 3 && this.calendar.getWeekday(date) !== 5 && this.calendar.getWeekday(date) !== 6);
};

But how could i reach it dynamically?

The function where i get the number values to set in is got from the following map:

dayArray.map((g) => {
  console.log(dayIndiciesByDayName[g.toLowerCase()] + 1); // here i get for each element in my array get from API the number to be set in return
});

Upvotes: 3

Views: 149

Answers (1)

Poul Kruijt
Poul Kruijt

Reputation: 71901

So, would this work. By using a utility function which creates the method?

someApiCall(): void {
  const apiReturn = [ 3, 5, 6 ];

  this.markDisabled = this.markDisableFunction(apiReturn);
}

markDisableFunction(includeDays: number[]): (date: NgbDate) => boolean {
  return (date: NgbDate) => !includeDays.includes(this.calendar.getWeekday(date))
}

Upvotes: 4

Related Questions