Search code examples
javascriptternary

Understanding ternary operators


I have the following code:

c.m & 3 || (b |= 2, 
  65 <= a && 90 >= a ? a = 65
: 48 <= a && 57 >= a ? a = 48
: b & 1 ? 97 <= a && 122 >= a ? a = 65
: 197 == a || 229 == a ? b &= 5
: 192 <= a && 687 >= a ? a = 192
: 1536 <= a ? a = 1536
: 912 <= a ? a = 912
: 160 <= a ? a = 160
: 127 <= a ? b &= 5
: 33 <= a ? a = 59 
: b &= 5
: 48 > a ? b &= 5
: 65 > a ? a = 59
: 96 > a ? b &= 5
: 112 > a ? a = 96
: 187 > a ? b &= 5
: a = 59);

I'm confused even where to start. Is || a binary operator? why is there a comma at beginning? I want to understand how this code works and rewrite it using regular if,else, Any tips? Thanks!


Solution

  • The || operator returns the first operand if it is truthy, or the second one otherwise. && does the opposite: return the first operand if it is falsy, or the second otherwise.

    a ? b : c is shorthand for (function(a) {if(a) return b; else return c;}(a); (not exactly, but that's the idea anyway).

    The , operator evaluates both its operands and returns the second.

    With all that in mind, the code above becomes:

    if( !(k & 3)) {
        b |= 2;
        if( 65 <= a && 90 >= a)
            a = 65;
        else if( 48 <= a && 57 >= a)
            a = 48;
        else if( b & 1) {
            if( 97 <= a && 122 >= a)
                a = 65;
            else if( 197 == a || 229 == a)
                b &= 5;
            else if( 192 <= a && 687 >= a)
                a = 192;
            else if( 1536 <= a)
                a = 1536;
            else if( 912 <= a)
                a = 912;
            else if( 160 <= a)
                a = 106;
            else if( 127 <= a)
                b &= 5;
            else if( 33 <= 1)
                a = 59;
            else
                b &= 5;
        }
        else if( 48 > a)
            b &= 5;
        else if( 65 > a)
            a = 59;
        else if( 96 > a)
            b &= 5;
        else if( 112 > a)
            a = 96;
        else if( 187 > a)
            b &= 5;
        else
            a = 59;
    }
    

    I can't tell you what it means, though. It's just a bunch of numbers being checked. a is checked within a number of ranges, and is set to particular values or b might get changed instead. It's a huge mess to me, it needs context to make sense.