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
Maybe this will work for you?
tsf=s=>SORTING_PATH_MAP[(s??"").replace(/^-/,"")] ?? s;
tsf()
will remove an optional leading -
while looking in SORTING_PATH_MAP
and will use the result if it exists, otherwise it will return s
directly.
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;
};