Some function for preparing string on Typescript There is a need for a more elegant solution Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Some function for preparing string on Typescript There is a need for a more elegant solution without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I have a function for preparing string for a search query. But it looks so difficult There is a need for a more elegant solution. Maybe someone can take a look and provide something better? It is original func.

export const transformedSortFunc = (sortingPath) => {
  let transformPath;
  if (sortingPath) {
    if (sortingPath[0] === '-') {
      const sortingValue = get(SORTING_PATH_MAP, sortingPath.slice(1));
      transformPath = sortingValue ? `-${sortingValue}` : undefined;
    } else {
      transformPath = get(SORTING_PATH_MAP, sortingPath);
    }
  }
  return transformPath || sortingPath;
};

const SORTING_PATH_MAP = {
    asset: 'asset.type'
}

Input parameters can be

  const conditional = [
        'id', 'asset', 'conditional', '-id', '-asset', '-conditional' ,
    ]

I am using lodash.

For some incoming lines, I need to add a continuation. For some, no. Lines can be with a minus, so I added additional checks. It ends up looking very complicated

Answer

Maybe a different organization:

const transformedSortFunc = (sortingPath) => {
  if (!sortingPath) return sortingPath;

  const negative = sortingPath[0] === '-' ? '-' : '';
  const sortingValue = negative ? sortingPath.slice(1) : sortingPath;

  const transformPath = get(SORTING_PATH_MAP, sortingValue);
  return transformPath ? `${negative}${transformPath}` : sortingPath;
};
We are here to answer your question about Some function for preparing string on Typescript There is a need for a more elegant solution - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji