understanding Complex inArray ternary operator

Alexander Solonik

I was just going through the inArray method code and came across the following ::

inArray: function (elem, arr, i) {
    var len;

    if (arr) {
        if (indexOf) {
            return indexOf.call(arr, elem, i);
        }

        len = arr.length;
        i = i ? i < 0 ? Math.max(0, len + i) : i : 0;

        for (; i < len; i++) {
            // Skip accessing in sparse arrays
            if (i in arr && arr[i] === elem) {
                return i;
            }
        }
    }

    return -1;
},

now i understand how tenary operators work , but can somebody tell me , how the below line of code really works ? is it even a ternary operator ?

i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;

or is it some kind of a new construct in JS ?

Thank you.

Alex-z.

Tushar

Original Statement:

i = i ? i < 0 ? Math.max(0, len + i) : i : 0;

To understand it better,

i = i ? (i < 0 ? Math.max(0, len + i) : i) : 0;
//      ^                                ^

Yes, this is nested ternary operator ? :.

Following is the if else representation of the above statement, represented in if..else step by step.

if (i) {
    i = i < 0 ? Math.max(0, len + i) : i;
} else {
    i = 0;
}

It works as follow:

if (i) {
    if (i < 0) {
        i = Math.max(0, len + i);
    } else {
        i = i;
    }
} else {
    i = 0;
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related