Home > Mobile >  How to remove my nested ternary expressions in my code?
How to remove my nested ternary expressions in my code?

Time:01-29

I would like to clean up my code but I can't. I would like to get rid of the nested ternary expressions. I work with react js 17.0.2. Do you have any ideas to help me?

  const buildNewFilters = (query, filtersIndex: Array<string>) => {
    const newFilters = {};
    for (let i = 0; i < filtersIndex.length; i  ) {
      newFilters[filtersIndex[i]] = router.query[filtersIndex[i]] ? typeof router.query[filtersIndex[i]] == ('string' || 'number') ? [router.query[filtersIndex[i]]] : router.query[filtersIndex[i]] : undefined
      if (filtersIndex[i] === 'designers' && newFilters.designers) {
        newFilters.designers = newFilters.designers.map(designer => parseInt(designer));
      }
    }
    return newFilters;
  };

CodePudding user response:

If you are not used to working with ternary operators, I understand that it's not easy to refactor the code. First, you can read about what ternary expressions are and try them out in the Mozilla Documentation about ternary operators. Basically the part of the code before the ? evaluates to either true or false and if it evaluates to true, the part before the subsequent : is executed (in your case assigned to the variable newFilters[filtersIndex[i]], otherwise the part after the : will be assigned to the variable.

My tip would be to put the line you want to refactor in a text editor to experiment with it, and add line breaks and/or tabs after the ? and : signs to see the structure better and to see what is happening at each step.

CodePudding user response:

if (router.query[filtersIndex[i]]) {
   if (typeof router.query[filtersIndex[i]] == ("string" || "number")) {
     newFilters[filtersIndex[i]] = [router.query[filtersIndex[i]]];
    } else {
      newFilters[filtersIndex[i]] = router.query[filtersIndex[i]];
    }
  } else {
    newFilters[filtersIndex[i]] = undefined;
  }
  •  Tags:  
  • Related