Home > other >  Please do I interprete this ternary operator?
Please do I interprete this ternary operator?

Time:02-07

Please if this function was to be converted to a "normal" if else statement, how would it look like?

export const orderArr = (arr: any[], key: string) => arr.sort((a, b) => ((a[key] > b[key]) ? 1 : (a[key] === b[key]) ? ((a[key] > b[key]) ? 1 : -1) : -1));

I want to add another condition, but I'm finding it hard to read or digest the current flow.

CodePudding user response:

I am not sure about sort function's structure but the if statement might look like below:

export const orderArr = (arr: any[], key: string) => arr.sort((a, b) => 
{
    if(a[key] > b[key] || a[key] === b[key]){
        return 1;
    } else {
        return -1;
    }
}
);

CodePudding user response:

export const orderArr = (arr: any[], key: string) => arr.sort((a, b) => ((a[key] > b[key]) ? 1 : (a[key] === b[key]) ? ((a[key] > b[key]) ? 1 : -1) : -1));

is equal to:

export const orderArr = (arr: any[], key: string) => {
    return arr.sort((a, b) => {
        if (a[key] > b[key]) {
            return 1;
        } else if (a[key] === b[key]) {
            if (a[key] > b[key]) {
                return 1;
            } else {
                return -1;
            }
        } else {
            return -1;
        }
    })
}

I'm strongly believe it's not necessary to use 3 level nested ternary operators anywhere 'cause it's huge code readability sacrifice for no reason.

Feel free to rewrite method to common if/else or switch statements to keep your code clear.

CodePudding user response:

That's correct. You shouldn't nest ternary operators, thats bad practice.

For your case, not sure what type of data you're comparing. Examples: if it's number, you can use a[key] - b[key]. If it's string - a[key].localeCompare(b[key])

CodePudding user response:

Without any regards to logics, this is the if else version of the code:

const orderArr = (arr, key) => {
  return (
    arr.sort( (a,b) => {
      if(a[key] > b[key]) {
        return 1
    }
    else if(a[key] === b[key]) {
        if (a[key] > b[key])
        return 1
        else return -1
    } else {
      return -1
    }
    })
  )
}

CodePudding user response:

if ((a[key] > b[key])) {
    1
} else {
    if ((a[key] === b[key])) {
        if (((a[key] > b[key])) {
            1
        } else {
            -1)
        }
    } else {
        -1)
    }
}

Generated from: https://converter.website-dev.eu/

  •  Tags:  
  • Related