Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

TypeScript – How can i deal with multiple IFs

I was trying to do a "multiple filter" in TS, So…

If i send nothing -> it returns all products normally;

But if i send some params -> it returns products filtered by the params.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

(I used colors just for the example)

async load(params: params): LoadProducts.Result => {
  const products = [];

  if (params) {
    if (params.red != undefined) // products.push( ...load.redProducts() );
    if (params.blue != undefined) // products.push( ...load.blueProducts() );
    if (params.green != undefined) // products.push( ...load.greenProducts() );
    if (params.yellow != undefined) // products.push( ...load.yellowProducts() );
  } else {
    // products.push( ...load.products() );
  }

  return products;
}

Type of request:

type params = {
  filter?: {
    red?:  boolean;
    blue?: boolean;
    green?: boolean;
    yellow?: boolean;
  };
};

Example of request:

{
  "filter": {
    "red": true,
    "blue": true
  }
}

How can I deal with the multiple IFs to verify the params, because each has its own function to load and I want to add more filters.

>Solution :

You have not included a minimal, reproducible example, but based on what you have shown, you can use a (map-like) array of tuples and iterate over it:

const colorFns = [
  ['red', load.redProducts.bind(load)],
  ['blue', load.blueProducts.bind(load)],
  // etc...
] as const;

async load(params: params): LoadProducts.Result => {
  const products = [];

  if (params) {
    for (const [color, fn] of colorFns) {
      if (params[color] != undefined) products.push(...fn());
    }
  } else {
    // products.push( ...load.products() );
  }

  return products;
}

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading