Coyolero
Coyolero

Reputation: 2433

Conditionally chaining array methods

How do I make the array methods optional?

Leets say I have this code but I want to filter or map optional

const ages = data
  .filter(isDog)
  .map(dogYears)
  .reduce(sum);

So I will do something like

let result

if(useFilter) {
  result = data.filter(isDog)
}

result
  .map(dogYears)
  .reduce(sum);

I know there should be a more compact and SOLID way of doing it

Upvotes: 3

Views: 182

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371193

You could use the ternary operator to conditionally transform the initial array, in a single line, without any reassignment:

// const result = [ ... ]

const output = (useFilter ? result.filter(isDog) : result)
  .map(dogYears)
  .reduce(sum);

Upvotes: 6

Related Questions