Title: Some function for preparing string on Typescript There is a need for a more elegant solution
Tags: javascript
Question: 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) =&gt; {
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
Comment: You are right. That was typescript. But it does not matter for this implementation.  But anyway I removed the type declaration...

Comment: That looks like Typescript, not Javascript.

Comment: I suggest you remove that from your example then.

Comment: @connexo only the `: string` is TS which is hardly relevant anyway.

Here is the accepted answer: Maybe a different organization:
const transformedSortFunc = (sortingPath) =&gt; {
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;

Here is another answer: Maybe this will work for you?
tsf=s=&gt;SORTING_PATH_MAP[(s??&quot;&quot;).replace(/^-/,&quot;&quot;)] ?? 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.
Comment for this answer: It looks great, but the case with a "minus" from a constant needs to be slightly modified does not work.
But thanks for the idea, I think I'll work in this direction

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 2, 'CommentCount': 4, 'ContentLicense': 'CC BY-SA 4.0', 'CreationDate': '2022:00:02/06/22', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<javascript>', 'Title': 'Some function for preparing string on Typescript There is a need for a more elegant solution', 'ViewCount': 57, 'id': 71008669, 'user_AboutMe': None, 'user_AccountId': 10134339.0, 'user_DisplayName': 'pridan', 'user_Reputation': 163.0, 'user_Views': 14.0, 'user_id': 7613573.0}}