简体   繁体   中英

Try to figure it out how to translate a long ternary operator with more than one condition into long if statement

I found online this snippet and I'm trying to figure it out how to translate it in a plan if statement:

return a.price > b.price ? 1 : a.price === b.price ? a.name > b.name ? 1 : -1 : -1;

In my opinion, if I had written an if statement:

if (a.price > b.price) {
    return 1;
} else if (a.price === b.price) {
    return 1;
} else if (a.name > b.name) {
    return 1;
} else {
    return -1;
}

But I'm not quite sure what it means a question mark and right after another question mark, same problem with a colon. I get that, the colon, in this case, could be an else if statement (in that order), but what about the question mark? any hint?

Your first part is right, but the next isn't. This:

a.price === b.price ? a.name > b.name ? 1 : -1 : -1;

separated out, looks like:

a.price === b.price
  ? (
    a.name > b.name
      ? 1
      : -1
    )
  : -1;

The inner conditional is a.name > b.name ? 1 : -1 a.name > b.name ? 1 : -1 .

If the prices are not equal, -1 is returned. Otherwise, the names are compared. To translate this correctly:

if (a.price > b.price) {
  return 1;
}
if (a.price !== b.price) {
  return -1;
}
if (a.name > b.name) {
  return 1;
}
return -1;

If this is being used for a .sort callback, another option which is equivalent to the above is:

return a.price - b.price || a.name.localeCompare(b.name)

Grouping it like this will help

a.price > b.price ? 1 : (a.price === b.price ? (a.name > b.name ? 1 : -1) : -1)

a.price > b.price ? 1 : x
x = a.price === b.price ? y : -1;
y =  a.name > b.name ? 1 : -1; 

The translated IF ELSE would be

if(a.price > b.price){
    return 1
} else {
    if(a.price === b.price){
        if(a.name > b.name){
            return 1;
        } else {
            return -1;
        }
    } else {
        return -1;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM